function showCalendar_month()
{
    global $_GET;
    extract($_GET);
    // check diary view permissions
    if (!isset($view_diary) || $view_diary == USER_NAME) {
        $view_diary = USER_NAME;
    } else {
        // make sure user has read privileges on this diary
        $view_diary = remval($view_diary);
        db_conn("cubit");
        $sql = "SELECT * FROM diary_privileges\r\n\t\t\tWHERE priv_owner='" . USER_NAME . "' AND diary_owner='{$view_diary}' AND privilege='R'";
        $rslt = db_exec($sql) or errDie("Error reading diary diary privileges.");
        if (pg_num_rows($rslt) < 1) {
            return "<li class=err>You do not have sufficient permissions to read this diary.</li>";
        }
    }
    if (!isset($month)) {
        $month = date("m");
    }
    if (!isset($year)) {
        $year = date("Y");
    }
    $monthview = generateMonthView_large($month, $year, $view_diary);
    $OUTPUT = "\r\n\t<table width='750'>\r\n\t<tr>\r\n\t\t<td align=center valign=top>{$monthview}</td>\r\n\t</tr>\r\n\t</table>";
    return $OUTPUT;
}
function OUTPUT($_POST)
{
    extract($_POST);
    $typeid = remval($typeid);
    # Set up table to display in
    $OUTPUT .= "<td valign=top width='33%'>\r\n<table border=0 width='90%'>\r\n<tr><td align=center nowrap><h3>Document Data</h3></td></tr>\r\n<tr><th>Type</th><th>Ref</th><th>Document</th><th>Date</th><th>Description</th><th>Filename</th></tr>";
    if ($typeid != '0') {
        $whe = "AND typeid='{$typeid}' ";
    } else {
        $whe = "";
    }
    # Connect to database
    //db_conn (YR_DB);
    db_conn("yr2");
    # Query server
    $i = 0;
    $sql = "SELECT * FROM documents WHERE div = '" . USER_DIV . "' {$whe} ORDER BY docname ASC";
    $docRslt = db_exec($sql) or errDie("Unable to retrieve Documents from database.");
    if (pg_numrows($docRslt) < 1) {
        return "<li>There are no Documents in Cubit.</li>\r\n\t\t\t <p>\r\n\t\t\t <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=15%>\r\n\t\t<tr><td><br></td></tr>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='docadd.php'>Add Document</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='docview.php'>View Documents</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='docman-index.php'>Back</a></td></tr>\r\n\t\t</table>";
    }
    while ($doc = pg_fetch_array($docRslt)) {
        $OUTPUT .= "<tr class='" . bg_class() . "'><td>{$doc['typename']}</td><td>{$doc['docref']}</td><td>{$doc['docname']}</td><td>{$doc['docdate']}</td><td>{$doc['descrip']}</td><td>{$doc['filename']}</td><td><a href='docedit.php?docid={$doc['docid']}'>Edit</a></td>";
        $OUTPUT .= "<td><a href='docdload.php?docid={$doc['docid']}'>Download</a></td><td><a href='docrem.php?docid={$doc['docid']}'>Remove</a></td></tr>";
        $i++;
    }
    $OUTPUT .= "</table></td>";
    return $OUTPUT;
}
function settings()
{
    extract($_POST);
    db_conn('cubit');
    $err = "";
    $save = false;
    if (isset($from)) {
        $save = true;
        require_lib("validate");
        $v = new validate();
        $v->isOk($sig, "string", 0, 255, "Invalid signature.");
        $v->isOk($from, "email", 1, 255, "Invalid from e-mail address.");
        $v->isOk($reply, "email", 0, 255, "Invalid reply e-mail address.");
        $v->isOk($host, "string", 1, 255, "Invalid smtp server. You need to fill in the SMTP HOST field, you can get this from your ISP.<br>\n\t\t\t\tExamples: smtp.saix.net OR smtp.mweb.co.za");
        if ($v->isError()) {
            $err = $v->genErrors();
        } else {
            $sig = remval($sig);
            $from = remval($from);
            $reply = remval($reply);
            $host = remval($host);
            $Sl = "SELECT * FROM esettings";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                $Sl = "INSERT INTO esettings(sig,fromname,reply,smtp_host,smtp_auth,smtp_user,smtp_pass) VALUES\n\t\t\t\t('{$sig}','{$from}','{$reply}','{$host}','0','','')";
                $Ri = db_exec($Sl);
            } else {
                $Sl = "UPDATE esettings SET sig='{$sig}',fromname='{$from}',reply='{$reply}',smtp_host='{$host}'";
                $Ri = db_exec($Sl);
            }
            r2sListRestore("emailsettings");
        }
    }
    $Sl = "SELECT * FROM esettings";
    $Ri = db_exec($Sl);
    $sd = pg_fetch_array($Ri);
    if (!$save) {
        $ex = "<li class=err>Please set your email settings & then click 'Update'</li>";
    } else {
        $ex = "<li class=err>Email settings saved</li>";
    }
    if (pg_num_rows($Ri) < 1) {
        $sd['sig'] = "";
        $sd['fromname'] = "";
        $sd['reply'] = "";
        $sd['smtp_host'] = "smtp.saix.net";
        $exx = "<li class=err>These are default settings. If these settings do not work, contact your ISP for correct details.</li>";
    } else {
        $exx = "";
    }
    $sd = array_merge($sd, $_POST);
    if (!isset($retdata)) {
        $retdata = "";
    }
    $out = "<h3>Email Settings</h3>\n\t{$exx}\n\t{$ex}\n\t<br />\n\t{$err}\n\t<table " . TMPL_tblDflts . ">\n\t<form action='" . SELF . "' method=post>\n\t{$retdata}\n\t<tr>\n\t\t<th colspan='2'>Settings</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td align='center' colspan='2'><b>An asterisk (" . REQ . ") symbol marks required fields.</b></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Signature</td>\n\t\t<td><input type='text' size='25' name='sig' value='{$sd['sig']}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>" . REQ . " From E-mail Address</td>\n\t\t<td><input type='text' size='25' name='from' value='{$sd['fromname']}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Reply To E-mail Address</td>\n\t\t<td><input type='text' size='25' name='reply' value='{$sd['reply']}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>" . REQ . " SMTP Server</td>\n\t\t<td><input type='text' size='25' name='host' value='{$sd['smtp_host']}'></td>\n\t</tr>\n\t<tr>\n\t\t<td colspan=2 align=right><input type=submit value='Update &raquo;'></td>\n\t</tr>\n\t</form>\n\t</table>\n\t<p>\n\t<table boder=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\n\t</table>";
    return $out;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    $terms = remval($terms);
    if (strlen($terms) > 1024) {
        return "<h3>Company Terms Too Long</h3>";
    }
    db_connect();
    $sql = "UPDATE compinfo SET terms = '{$terms}'";
    $allow = db_exec($sql) or errDie("Unable To Update Company Terms");
    return "\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><h3>Company Terms have been Successfully Updated</h3></h3></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t</table>";
}
function slct($err = "")
{
    global $_POST;
    extract($_POST);
    if (isset($letters)) {
        $letters = remval($letters);
        $whe = "AND lower(surname) LIKE lower('%{$letters}%')";
    } else {
        $letters = "";
        $whe = "";
    }
    db_connect();
    $sql = "SELECT * FROM customers WHERE div = '" . USER_DIV . "' AND location != 'int' {$whe} ORDER BY lower(surname) ASC";
    $cusRslt = db_exec($sql) or errDie("Could not retrieve Customers Information from the Database.", SELF);
    $custs = "<select name='sval'>";
    if (pg_numrows($cusRslt) < 1) {
        $custs .= "<option value='-S'></option>";
    }
    while ($cus = pg_fetch_array($cusRslt)) {
        $custs .= "<option value='{$cus['cusnum']}'>{$cus['surname']}</option>";
    }
    $custs .= "</select>";
    $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "'";
    $Rs = db_exec($sql);
    $numrows = pg_numrows($Rs);
    if (empty($numrows)) {
        return "<li class='err'> There are no accounts held at the selected Bank.</li>\n\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
    }
    $banks = "<select name='bankid'>";
    while ($acc = pg_fetch_array($Rs)) {
        $banks .= "<option value={$acc['bankid']}>{$acc['accname']} - {$acc['bankname']} ({$acc['acctype']})</option>";
    }
    $banks .= "</select>";
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
    $deptRslt = db_exec($sql);
    $depts = "<select name='cval'>";
    if (pg_numrows($deptRslt) < 1) {
        $depts .= "<option value='-S'></option>";
    }
    while ($dept = pg_fetch_array($deptRslt)) {
        $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
    }
    $depts .= "</select>";
    //<tr class='bg-odd' ".ass("Select when the sale of non stock goods is a bank sale")."><td><input type=radio name=ctyp value='cb'>Bank Sale</td><td>$banks</td></tr>
    $details = "\n\t\t<center>\n\t\t<h3>New Recurring Non-Stock Invoice</h3>\n\t\t<h4>Customer Details</h4>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='slct'>\n\t\t\t<input type='hidden' name='starting' value=''>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$err}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Invoice Details </th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "' " . ass("Select when selling non stock goods to your customers") . ">\n\t\t\t\t<td><input type='radio' name='ctyp' value='s' checked='yes'> Select Customer</td>\n\t\t\t\t<td>{$custs}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "' " . ass("Select when the sale of non stock goods is a cash sale") . ">\n\t\t\t\t<td><input type='radio' name='ctyp' value='c'>Cash Sale</td>\n\t\t\t\t<td>{$depts}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "' " . ass("Select when the sale of non stock goods is not a cash sale") . ">\n\t\t\t\t<td><input type='radio' name='ctyp' value='ac'>Ledger Accounts Sale</td>\n\t\t\t\t<td></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Search by surname</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='text' size='10' name='letters' value='{$letters}'></td>\n\t\t\t\t<td><input type='submit' value='Search &raquo;'></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td align='center'></td>\n\t\t\t\t<td align='center'><input type='submit' name='button' value='Continue &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>";
    return $details;
}
function confirm($_GET)
{
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
    $v->isOk($body, "string", 1, 800, "Invalid to Email Message.");
    # mix dates
    $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    if (!checkdate($from_month, $from_day, $from_year)) {
        $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
    }
    if (!checkdate($to_month, $to_day, $to_year)) {
        $v->isOk($todate, "num", 1, 1, "Invalid to date.");
    }
    $type = remval($type);
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    $out = "\n\t\t\t<h3>Statements to be e-mailed: {$fromdate} TO {$todate}, {$type}</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='send'>\n\t\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t\t\t\t<input type='hidden' name='type' value='{$type}'>\n\t\t\t\t<input type='hidden' name='body' value='{$body}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Acc Num</th>\n\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t<th>Email Address</th>\n\t\t\t\t</tr>";
    $i = 0;
    db_conn('cubit');
    foreach ($cids as $id) {
        $id += 0;
        $Sl = "SELECT accno,surname,email FROM customers WHERE cusnum='{$id}'";
        $Ri = db_exec($Sl);
        $cd = pg_fetch_array($Ri);
        $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['accno']}</td>\n\t\t\t\t\t<td>{$cd['surname']}</td>\n\t\t\t\t\t<td>{$email[$id]}</td>\n\t\t\t\t</tr>\n\t\t\t\t<input type='hidden' name='cids[]' value='{$id}'>\n\t\t\t\t<input type='hidden' name='email[{$id}]' value='{$email[$id]}'>";
        $i++;
    }
    $out .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th colspan='3'>Message That Will Display In The Email</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='3'>" . nl2br($body) . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo Correction'></td>\n\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Send Emails &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>";
    return $out;
}
function showCalendar_day()
{
    global $_GET;
    // get the post_vars
    extract($_GET);
    // create the day view and month view data
    if (!isset($view_diary) || $view_diary == USER_NAME) {
        $view_diary = USER_NAME;
    } else {
        // make sure user has read privileges on this diary
        $view_diary = remval($view_diary);
        db_conn("cubit");
        $sql = "SELECT * FROM diary_privileges\r\n\t\t\tWHERE priv_owner='" . USER_NAME . "' AND diary_owner='{$view_diary}' AND privilege='R'";
        $rslt = db_exec($sql) or errDie("Error reading diary diary privileges.");
        if (pg_num_rows($rslt) < 1) {
            return "<li class=err>You do not have sufficient permissions to read this diary.</li>";
        }
    }
    $DayView = createDayView($mday, $month, $year, $view_diary);
    $MonthViews = createMonthViews($month, $year, $view_diary);
    $Notices = createNotices($mday, $month, $year, $view_diary);
    $OUTPUT = "\r\n\t<center><table width='750'>\r\n\t\t<tr>\r\n\t\t\t<td width=550 valign=top>\r\n\t\t\t\t{$DayView}\r\n\t\t\t</td>\r\n\t\t\t<td width=200 valign=top>\r\n\t\t\t\t{$MonthViews}\r\n\t\t\t\t<hr>\r\n\t\t\t\t{$Notices}\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table></center>\r\n\t";
    return $OUTPUT;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST, "<li class='err'>Customer is overdue, account blocked!</li>");
    }
    $pcredit += 0;
    $pcash += 0;
    $pcheque += 0;
    $pcc += 0;
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            //$v->isOk ($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            if (is_numeric($stkid)) {
                $sql = "SELECT units, stkcod FROM cubit.stock WHERE stkid='{$stkid}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($stock_units, $stock_code) = pg_fetch_array($stock_rslt);
                if ($qtys[$keys] > $stock_units) {
                    $v->addError(0, "Not enough stock available for {$stock_code}");
                }
            }
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (2): <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && strlen($sernos[$keys]) <= 0 && strlen($sernos_ss[$keys]) <= 0) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (1): <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    $des = remval($des);
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    if (strlen($client) < 1) {
        $client = "Cash Sale";
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # 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>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    # 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 = '{$deptid}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM pinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } else {
                if (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                    $accounts[$keys] += 0;
                    # Get selamt from selected stock
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    $ad = pg_fetch_array($Ri);
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                    $vatcodes[$keys] += 0;
                    $accounts[$keys] += 0;
                    $descriptions[$keys] = remval($descriptions[$keys]);
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost,\n\t\t\t\t\t\t\t\tamt, disc, discp, ss, serno, div,vatcode,description,\n\t\t\t\t\t\t\t\taccount)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '','" . USER_DIV . "',\n\t\t\t\t\t\t\t\t'{$vatcodes[$keys]}','{$descriptions[$keys]}',\n\t\t\t\t\t\t\t\t'{$accounts[$keys]}')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                } else {
                    # get selamt from selected stock
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    # Calculate the Discount discount
                    if ($disc[$keys] < 1) {
                        if ($discp[$keys] > 0) {
                            $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                        }
                    } else {
                        $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty,\n\t\t\t\t\t\t\t\tunitcost, amt, disc, discp, ss, serno, div,vatcode)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}',\n\t\t\t\t\t\t\t\t'" . USER_DIV . "','{$vatcodes[$keys]}')";
                    // $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]','$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                    if (strlen($sernos[$keys]) > 0) {
                        ext_resvSer($sernos[$keys], $stk['stkid']);
                    }
                    # update stock(alloc + qty)
                    $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    // 		/*if(pg_num_rows($Ri)>0) {
    // 			*/$taxex += $delchrg;
    // 		}
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
        }
    } else {
        $cusacc = "";
    }
    //	die($cusnum);
    # insert invoice to DB
    $sql = "UPDATE pinvoices SET pcredit='{$pcredit}',cusnum='{$cusnum}',delvat='{$delvat}',rounding='{$rounding}',pcash='{$pcash}',pcheque='{$pcheque}',\n\t\tpcc='{$pcc}',deptid='{$deptid}',deptname = '{$dept['deptname']}', cusname = '{$client}', cordno = '{$cordno}', ordno = '{$ordno}',chrgvat = '{$chrgvat}',\n\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}',\n\t\tbalance = '{$pcredit}', comm = '{$comm}', discount='{$traddiscmt}', delivery='{$delexvat}', vatnum='{$vatnum}', cusacc = '{$cusacc}', telno='{$telno}'\n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updatin
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt,\n\t\t\t\t\tdisc, discp, ss, serno, div)\n\t\t\t\tVALUES('{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}',\n\t\t\t\t\t'{$s['selamt']}', '0', '0','{$bar}', '{$serno_bar}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        #check for credit limit
        if ($cusnum != "0") {
            #customer is selected ... get info
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND location != 'int' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            if (pg_numrows($custRslt) < 1) {
                $cust['balance'] = "0";
                $cust['creditlimit'] = "0";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            #customer is set check for response
            if ($pcredit + $cust['balance'] > $cust['credlimit']) {
                #limit reached ... check for 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 ...
                        return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                    }
                }
                # Check permissions
                if (!perm("invoice-limit-override.php")) {
                    return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                }
            }
        }
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\t\t(You can only overpay with cash)</li>");
        }
        # insert quote to DB
        $sql = "UPDATE pinvoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "\n\t\t\t\t\t<script>printer2('pos-invoice-print.php?invid={$invid}');</script>\n\t\t\t\t\t<input type='button' value='Create New POS Invoice' onClick=\"move('pos-invoice-new-no-neg.php');\">";
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write_data($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = remval($value);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        return $confirmCust;
    }
    db_conn('cubit');
    pglib_transaction("begin");
    $h = 0;
    $datemade = date("Y-m-d");
    $datefor = $date;
    $userfor = USER_NAME;
    $Sl = "DELETE FROM die WHERE datefor='{$datefor}' AND userfor='global'";
    $Rs = db_exec($Sl) or errDie("Unable to access database.");
    while ($h < 24) {
        if ($h < 10) {
            $h = "0" . $h;
        }
        $m = 0;
        while ($m < 60) {
            if ($m == 0) {
                $m = "00";
            }
            $t = "{$h}" . "{$m}";
            $tt = ${$t};
            $time = $t;
            $des = $tt;
            if (strlen($des) > 0) {
                $rem_date = substr($remops[$t], 0, 10);
                $rem_time = substr($remops[$t], 11, 4);
                //print "date: $rem_date time: $rem_time<br>";
                $Sl = "INSERT INTO die (datemade,datefor,userfor,time,des,remop,remdate,remtime,rem) VALUES ('{$datemade}','{$datefor}','global','{$time}','{$des}','{$rem_Options[$t]}','{$rem_date}','{$rem_time}','0')";
                $Rs = db_exec($Sl) or errDie("Unable to access database.");
            }
            $m = $m + 30;
        }
        $h++;
    }
    pglib_transaction("commit");
    header("Location: glodiary.php");
    exit;
    $write_data = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t <tr><th>Diary modified</th></tr>\r\n\t <tr class=datacell><td>Diary has been modified.</td></tr>\r\n\t</table>\r\n\t<p>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t <tr><th>Quick Links</th></tr>\r\n\t <tr class='bg-odd'><td><a href='glodiary.php'>Global Diary</a></td></tr>\r\n\t <tr class='bg-odd'><td><a href='index_die.php'>Diary</td>\r\n\t <tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $write_data;
}
function seltoken()
{
    global $_POST;
    extract($_POST);
    if (!isset($name)) {
        $name = "";
    }
    if (!isset($subject)) {
        $subject = "";
    }
    if (!isset($notes)) {
        $notes = "";
    }
    $name = remval($name);
    $subject = remval($subject);
    $notes = remval($notes);
    $whe = "";
    $csc = 0;
    if (!isset($team)) {
        $team = 0;
        $user = 0;
        $cat = 0;
        $csc = 0;
    } else {
        $team += 0;
        $user += 0;
        $cat += 0;
        $csc += 0;
    }
    if ($team == 0) {
        db_conn('crm');
        $Sl = "SELECT teamid FROM crms WHERE userid='" . USER_ID . "'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $crmdata = pg_fetch_array($Ri);
        $team = $crmdata['teamid'];
    }
    if ($team != 0) {
        $whe .= " AND teamid='{$team}' ";
    }
    if ($user != 0) {
        $whe .= " AND userid='{$user}' ";
    }
    if ($cat != 0) {
        $whe .= " AND catid='{$cat}' ";
    }
    if ($csc != 0) {
        if ($csc == 1) {
            $whe .= " AND csct='Contact' ";
        } elseif ($csc == 2) {
            $whe .= " AND csct='Customer' ";
        } elseif ($csc == 3) {
            $whe .= " AND csct='Supplier' ";
        }
    }
    if (strlen($name) > 0) {
        $whe .= " AND lower(name) LIKE lower('%{$name}%') ";
    }
    if (strlen($subject) > 0) {
        $whe .= " AND lower(sub) LIKE lower('%{$subject}%') ";
    }
    if (strlen($notes) > 0) {
        $whe .= " AND lower(notes) LIKE lower('%{$notes}%') ";
    }
    $date = date("Y-m-d");
    db_conn('crm');
    $Sl = "SELECT * FROM crms WHERE userid='" . USER_ID . "'";
    $Ry = db_exec($Sl) or errDie("Unable to get info from db.");
    if (pg_numrows($Ry) < 1) {
        return "You have not been set up to use query management.<br>\r\n\t\tPlease allocate yourself to a team.\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='crms-allocate.php'>Allocate users to Teams</a></td></tr>\r\n\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t<tr class='bg-odd'><td><a href='index.php'>My Business</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n\t\t</table>";
    }
    $crmdata = pg_fetch_array($Ry);
    if ($crmdata['teamid'] == 0) {
        return "You have not been set up to use query management.<br>\r\n\t\tPlease allocate yourself to a team.\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='crms-allocate.php'>Allocate users to Teams</a></td></tr>\r\n\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t<tr class='bg-odd'><td><a href='index.php'>My Business</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n\t\t</table>";
    }
    $Sl = "SELECT * FROM teams WHERE id='{$team}'";
    $Ry = db_exec($Sl) or errDie("Unable to get team data.");
    $teamdata = pg_fetch_array($Ry);
    $username = USER_NAME;
    $disdate = date("d-m-Y, l, G:i");
    $i = 0;
    $Sl = "SELECT * FROM teamlinks WHERE team='{$team}' ORDER BY num";
    $Ry = db_exec($Sl) or errDie("Unable to get teamlinks from system.");
    if (pg_numrows($Ry) < 1) {
        $teamlinks = "<tr><td>There are no links for this team. Select links under settings, view teams.</td></tr><tr><th>Quick Links</th></tr>\r\n                <tr class='bg-odd'><td align=center><a href='team-links.php?id={$crmdata['teamid']}'>Select Team Links</a></td></tr>";
    } else {
        $teamlinks = "";
        while ($linkdata = pg_fetch_array($Ry)) {
            $i++;
            $teamlinks .= "<tr class='" . bg_class() . "'><td><a target=_blank href='{$linkdata['script']}'>{$linkdata['name']}</a></td></tr>";
        }
    }
    $i = 0;
    $tokens = "";
    $Sl = "SELECT id,sub,name FROM tokens WHERE userid='" . USER_ID . "' {$whe} ORDER BY id";
    $Ry = db_exec($Sl) or errDie("Unable to get queries from db.");
    while ($tokendata = pg_fetch_array($Ry)) {
        $i++;
        $tokens .= "<tr class='" . bg_class() . "'><td>{$tokendata['id']}</td><td>{$tokendata['name']} - {$tokendata['sub']}</td><td><a href='tokens-manage.php?id={$tokendata['id']}'>Open</a></td></tr>";
    }
    $Sl = "SELECT id,name,username,sub,lastdate,opendate FROM tokens WHERE nextdate<='{$date}' {$whe} ORDER BY id";
    $Ry = db_exec($Sl) or errDie("Unable to get data from system.");
    if (pg_numrows($Ry) > 0) {
        $i = 0;
        $out = "<h3>All Outstanding Queries</h3>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<tr><th>No.</th><th>Subject</th><th>User</th><th>Date Opened</th><th>Last Date</th>\r\n\t\t<th>Options</th></tr>";
        while ($data = pg_fetch_array($Ry)) {
            $i++;
            $out .= "<tr class='" . bg_class() . "'><td>{$data['id']}</td><td>{$data['name']} - {$data['sub']}</td><td>{$data['username']}</td>\r\n\t\t\t<td>{$data['opendate']}</td><td>{$data['lastdate']}</td>\r\n\t\t\t<td><a href='tokens-manage.php?id={$data['id']}'>Open</a></td></tr>";
        }
        $out .= "</table>";
    } else {
        $out = "No Outstanding queries";
    }
    $Sl = "SELECT id,name,username,sub,lastdate,nextdate,opendate FROM tokens WHERE nextdate>'{$date}' {$whe} ORDER BY id";
    $Ry = db_exec($Sl) or errDie("Unable to get data from system.");
    if (pg_numrows($Ry) > 0) {
        $i = 0;
        $future = "<h3>All Forwarded Queries</h3>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<tr><th>No.</th><th>Subject</th><th>User</th><th>Date Opened</th><th>Last Date</th><th>Next Date</th>\r\n\t\t<th>Options</th></tr>";
        while ($data = pg_fetch_array($Ry)) {
            $i++;
            $future .= "<tr class='" . bg_class() . "'><td>{$data['id']}</td><td>{$data['name']} - {$data['sub']}</td><td>{$data['username']}</td>\r\n\t\t\t<td>{$data['opendate']}</td><td>{$data['lastdate']}</td><td>{$data['nextdate']}</td>\r\n\t\t\t<td><a href='tokens-manage.php?id={$data['id']}'>Open</a></td></tr>";
        }
        $future .= "</table>";
    } else {
        $future = "No forwarded queries.";
    }
    $cteams = explode("|", $crmdata['teams']);
    $Sl = "SELECT id,name FROM teams ORDER BY name";
    $Ry = db_exec($Sl) or errDie("Unable to get teams from system.");
    $teams = "<select name=team onChange='javascript:document.form.submit();'>";
    //$teams.="<option value='0'>All</option>";
    while ($tdata = pg_fetch_array($Ry)) {
        if ($team == 0) {
            if ($tdata['id'] == $crmdata['teamid']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
        } else {
            if ($team == $tdata['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
        }
        if (in_array($tdata['id'], $cteams)) {
            $teams .= "<option value='{$tdata['id']}' {$sel}>{$tdata['name']}</option>";
        }
    }
    $teams .= "</select>";
    $Sl = "SELECT userid,name,teamid FROM crms WHERE div='" . USER_DIV . "'";
    $Ry = db_exec($Sl) or errDie("Unable to get users from db.");
    $users = "<select name=user onChange='javascript:document.form.submit();'>";
    $users .= "<option value='0'>All</option>";
    while ($udata = pg_fetch_array($Ry)) {
        if ($user == $udata['userid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        if (in_array($udata['teamid'], $cteams)) {
            $users .= "<option value='{$udata['userid']}' {$sel}>{$udata['name']}</option>";
        }
    }
    $users .= "</select>";
    $Sl = "SELECT * FROM tcats WHERE div='" . USER_DIV . "' ORDER BY name";
    $Ry = db_exec($Sl) or errDie("Unable to get categories from system.");
    $cats = "<select name=cat onChange='javascript:document.form.submit();'>";
    $cats .= "<option value='0'>All</option>";
    while ($cdata = pg_fetch_array($Ry)) {
        if ($cat == $cdata['id']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $cats .= "<option value='{$cdata['id']}' {$sel}>{$cdata['name']}</option>";
    }
    $cats .= "</select>";
    $csc = 0;
    if ($csc == 0) {
        $op0 = "selected";
        $op1 = "";
        $op2 = "";
        $op3 = "";
    } elseif ($csc == 1) {
        $op0 = "";
        $op1 = "selected";
        $op2 = "";
        $op3 = "";
    } elseif ($csc == 2) {
        $op0 = "";
        $op1 = "";
        $op2 = "selected";
        $op3 = "";
    } elseif ($csc == 3) {
        $op0 = "";
        $op1 = "";
        $op2 = "";
        $op3 = "selected";
    }
    $cscs = "<select name=csc onChange='javascript:document.form.submit();'>\r\n\t<option value='0' {$op0}>All</option>\r\n\t<option value='1' {$op1}>Contacts</option>\r\n\t<option value='2' {$op2}>Customers</option>\r\n\t<option value='3' {$op3}>Suppliers</option>\r\n\t</select>";
    $out = "<h3>Select a Query</h3>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=750>\r\n\t<tr>\r\n\t\t<td colspan=3>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\r\n\t\t<tr>\r\n\t\t\t<td>\r\n\t\t\t<form action='tokens-new.php'>\r\n\t\t\t\t<input type=submit value='New Query &raquo;'>\r\n\t\t\t</form>\r\n\t\t\t</td>\r\n\t\t\t<td align=center><h3>Team: {$teamdata['name']} | User: {$username} | Date: {$disdate}</h3></td>\r\n\t\t</tr>\r\n\t\t</table>\r\n\t\t</td>\r\n\t</tr>\r\n\t<tr>\r\n\t\t<td colspan=2>\r\n\t\t<table border=0 cellpadding=2 cellspacing=1 width='100%'>\r\n\t\t<form action='" . SELF . "' method=post name=form>\r\n\t\t<input type=hidden name=key value='seltoken'>\r\n\t\t<tr><th colspan=2>Query Criteria</th></tr>\r\n\t\t<tr class='bg-odd'><td>Team</td><td>{$teams}</td></tr>\r\n\t\t<tr class='bg-even'><td>Users</td><td>{$users}</td></tr>\r\n\t\t<tr class='bg-odd'><td>Categories</td><td>{$cats}</td></tr>\r\n\t\t<tr class='bg-even'><td>Enquery By(name)</td><td><input type=text size=20 name=name value='{$name}'></td></tr>\r\n\t\t<tr class='bg-odd'><td>Subject</td><td><input type=text size=20 name=subject value='{$subject}'></td></tr>\r\n\t\t<tr class='bg-even'><td>Notes</td><td><input type=text size=20 name=notes value='{$notes}'></td></tr>\r\n\t\t<tr><td colspan=2 align=right><input type=submit value='Search &raquo;'></td></tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t</td>\r\n\t\t<td align=center valign=top>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<tr><th>{$teamdata['name']} Quick Links</th></tr>\r\n\t\t{$teamlinks}\r\n\t\t</table>\r\n\t\t</td>\r\n\t</tr>\r\n\t<tr>\r\n\t<td><br></td>\r\n\t</tr>\r\n\t<tr>\r\n\t\t<td width='22%'>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<form action='" . SELF . "' method=post>\r\n\t\t<input type=hidden name=key value='find'>\r\n\t\t<tr><th colspan=2>Search</th></tr>\r\n\t\t<tr class='bg-odd'><td colspan=2><li><a href='tokens-list-open.php'>List All Open Queries</a></li></td></tr>\r\n\t\t<tr class='bg-even'><td>Input No</td><td><input name=id type=text size=7></td></tr>\r\n\t\t<tr><td colspan=2 align=right><input type=submit name='search' value='Search &raquo;'></td></tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t</td>\r\n\t\t<td valign=top>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t<tr><th colspan=3>My Open Queries</th></tr>\r\n\t\t{$tokens}\r\n\t\t</table>\r\n\t\t</td>\r\n\t</tr>\r\n\t</table>\r\n\t{$out}\r\n\t<p>\r\n\t{$future}\r\n\t<p>\r\n\t<p>\r\n                <table border=0 cellpadding='2' cellspacing='1'>\r\n                <tr><th>Quick Links</th></tr>\r\n                <tr class='bg-odd'><td><a href='index.php'>My Business</a></td></tr>\r\n                <tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n                </table>";
    return $out;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details(array(), "<li class='err'>Invalid Customer</li>");
        //$cusnum = "";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($calloutid, "num", 1, 20, "Invalid Callout Document Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($def_travel, "string", 0, 255, "Invalid Default Travel.");
    $v->isOk($def_labour, "string", 0, 255, "Invalid Default Labour.");
    $v->isOk($calloutdescrip, "string", 0, 255, "Invalid Callout Description.");
    $v->isOk($sign, "string", 0, 255, "Invalid Sign Data.");
    $v->isOk($calloutp, "string", 1, 255, "Invalid sales person.");
    $v->isOk($call_day, "num", 1, 2, "Invalid Service Date day.");
    $v->isOk($call_month, "num", 1, 2, "Invalid Service Date month.");
    $v->isOk($call_year, "num", 1, 5, "Invalid Service Date year.");
    $odate = $call_year . "-" . $call_month . "-" . $call_day;
    if (!checkdate($call_month, $call_day, $call_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid callout Document Date.");
    }
    //	$v->isOk ($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    //	if(isset($qtys)){
    //		foreach($qtys as $keys => $qty){
    //
    //			$v->isOk ($qty, "num", 1, 10, "Invalid Quantity for product number : <b>".($keys+1)."</b>");
    //			$v->isOk ($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>.");
    //			if($qty < 1){
    //				$v->isOk ($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>".($keys+1)."</b>");
    //			}
    //		}
    //	}
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return details($_POST, $err);
    }
    # Get callout document info
    db_connect();
    $sql = "SELECT * FROM callout_docs WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
    $docRslt = db_exec($sql) or errDie("Unable to get callout document information");
    if (pg_numrows($docRslt) < 1) {
        return "<li>- Callout Document Not Found</li>";
    }
    $doc = pg_fetch_array($docRslt);
    # check if callout document has been printed
    if ($doc['accepted'] == "y") {
        $error = "<li class='err'>Error : Callout Document number <b>{$calloutid}</b> has already been printed.</li>";
        $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 = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM callout_docs_data WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $doc['deptid'] = $cust['deptid'];
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$doc['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # insert callout document to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this callout document
    $sql = "SELECT * FROM cubit.callout_docs_items WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    #while($stkt = pg_fetch_array($stktRslt)){
    #	update stock(alloc + qty)
    #	$sql = "UPDATE stock SET alloc = (alloc - '$stkt[qty]')  WHERE stkid = '$stkt[stkid]'";
    #	$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    #}
    # remove old items
    $sql = "DELETE FROM cubit.callout_docs_items WHERE calloutid='{$calloutid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                $Sl = "SELECT * FROM core.accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.callout_docs_items (\n\t\t\t\t\t\tcalloutid, whid, stkid, qty, \n\t\t\t\t\t\tunitcost, amt, div, \n\t\t\t\t\t\tdescription, account\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$calloutid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$unitcost[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t'{$descriptions[$keys]}','{$accounts[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                $wtd = $whids[$keys];
                # insert callout document items
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.callout_docs_items (\n\t\t\t\t\t\tcalloutid, whid, stkid, qty, \n\t\t\t\t\t\tunitcost, amt, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$calloutid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$unitcost[$keys]}','{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert callout document items to Cubit.", SELF);
                # update stock(alloc + qty)
                # $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                # $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $subtotal = sprint($sub);
    $SUBTOT = $sub;
    $TOTAL = $subtotal;
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    # insert callout documents to DB
    $sql = "\n\t\tUPDATE callout_docs \n\t\tSET cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', \n\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\tcusvatno = '{$cust['vatnum']}', calloutp = '{$calloutp}', odate = '{$odate}', subtot = '{$SUBTOT}', comm = '{$comm}', \n\t\t\tcalloutdescrip = '{$calloutdescrip}', sign = '{$sign}', def_travel = '{$def_travel}', def_labour = '{$def_labour}' \n\t\tWHERE calloutid = '{$calloutid}'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM callout_docs_data WHERE calloutid='{$calloutid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\tINSERT INTO callout_docs_data (\n\t\t\tcalloutid, dept, customer, \n\t\t\taddr1, div\n\t\t) VALUES (\n\t\t\t'{$calloutid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', \n\t\t\t'{$cust['addr1']}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert callout document data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # insert callout document to DB
        $sql = "UPDATE callout_docs SET done = 'y' WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update callout document status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Callout Document</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Callout Document for client <b>{$cust['cusname']} {$cust['surname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='callout-print.php?calloutid={$calloutid}'>Print Callout Document</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Callout Document Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Callout Document for client <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='callout-view.php'>View Callout Documents</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
Example #12
0
function account_info($_POST)
{
    $Out = "";
    #get & send vars
    foreach ($_POST as $key => $value) {
        ${$key} = remval($value);
        $Out .= "<input type=hidden name=\${$key} value='{$value}'>";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    # display errors, if any
    if ($v->isError()) {
        $errors = "";
        $Errors = $v->getErrors();
        foreach ($Errors as $e) {
            $errors .= "<li class=err>" . $e["msg"];
        }
        $errors .= "<input type=hidden name=errors value='{$errors}'>";
        return order($_POST, $errors);
    }
    if (isset($cc)) {
        $com = "Yes";
    } else {
        $com = "No";
    }
    $op = USER_NAME;
    db_conn("cubit");
    if (strlen($des) > 0) {
        $Sl = "INSERT INTO todos (datemade,timemade,op,des,com) VALUES ('{$datemade}','{$timemade}','{$op}','{$des}','{$com}')";
        $Rs = db_exec($Sl) or errDie("Unable to update database.", SELF);
    }
    if (isset($done)) {
        #get & send vars
        foreach ($done as $key => $value) {
            $Sl = "UPDATE todos SET com='Yes' WHERE id='{$key}'";
            $Rs = db_exec($Sl) or errDie("Unable to update database.", SELF);
        }
    }
    return order($_POST);
}
function printInv($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
    # mix dates
    $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    if (!checkdate($from_month, $from_day, $from_year)) {
        $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
    }
    if (!checkdate($to_month, $to_day, $to_year)) {
        $v->isOk($todate, "num", 1, 1, "Invalid to 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;
    }
    $accnum = remval($accnum);
    if (strlen($accnum) > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE lower(accno)=lower('{$accnum}')";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>Invalid account number</li>" . slct();
        }
        $cd = pg_fetch_array($Ri);
        $cusnum = $cd['cusnum'];
    }
    # Set up table to display in
    $printInv = "\n\t\t<h3>Paid Invoices</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t<th>Proforma Inv No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t</tr>";
    // Retrieve template setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $repr = "invoice-reprint-prd.php";
    } else {
        $repr = $template;
    }
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "new") {
        $pdf_repr = "pdf/pdf-tax-invoice.php";
    } else {
        $pdf_repr = "pdf/invoice-pdf-reprint-prd.php";
    }
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    if (isset($all)) {
        # Connect to database
        db_connect();
        $queries = array();
        for ($i = 1; $i <= 12; $i++) {
            $schema = (int) $i;
            $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".invoices WHERE done = 'y' AND odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "'";
        }
        $query = implode(" UNION ", $queries);
        $query .= " ORDER BY invid DESC";
    } else {
        # Connect to database
        db_connect();
        $queries = array();
        for ($i = 1; $i <= 12; $i++) {
            $schema = (int) $i;
            $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".invoices WHERE done = 'y' AND cusnum = '{$cusnum}' AND odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "'";
        }
        $query = implode(" UNION ", $queries);
        $query .= " ORDER BY invid DESC";
    }
    $invRslt = db_exec($query) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'>No previous finished invoices found.</li>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $prd = $inv["query_schema"];
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $bcurr = CUR;
            $det = "invoice-details-prd.php";
            $reprint = "<td><a target=_blank href='{$repr}?type=invpaidreprint&invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
            $note = "<td><a target=_blank href='invoice-note-prd.php?invid={$inv['invid']}&prd={$prd}'>Credit Note</a></td>";
            if ($inv['location'] == 'int') {
                $bcurr = $inv['currency'];
                $det = "intinvoice-details-prd.php";
                $reprint = "<td><a target='_blank' href='intinvoice-reprint-prd.php?invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
                $note = "";
            }
            $delnote = "<td><a target='_blank' href='invoice-delnote-prd.php?invid={$inv['invid']}&prd={$prd}'>Delivery Note</a></td>";
            $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?invid={$inv['invid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t</td>{$reprint}</td>\n\t\t\t\t\t<td><a href='{$pdf_repr}?invid={$inv['invid']}&prd={$prd}&type=invpaidreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t{$note}\n\t\t\t\t\t{$delnote}\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    $tot2 = sprint($tot2);
    // Layout
    if ($tot1 > 0) {
        $printInv .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='7'>Totals:{$i}</td>\n\t\t\t\t<td align='right'>{$tot1}</td>\n\t\t\t\t<td align='right' colspan='6'></td>\n\t\t\t</tr>";
    }
    $printInv .= "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\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='invoice-canc-view.php'>View Cancelled Invoices</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='invoice-unf-view.php'>View Incomplete Invoices</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='cust-credit-stockinv.php'>New Invoice</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $printInv;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    // prevent from updating
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST);
    }
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (!isset($bodydata)) {
        $bodydata = "";
    }
    if (!isset($counter)) {
        $counter = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    $des[$counter] = $bodydata;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (empty($ninv_year)) {
        list($ninv_year, $ninv_month, $ninv_day) = date("Y-m-d");
    }
    $odate = mkdate($ninv_year, $ninv_month, $ninv_day);
    $v->isOk($odate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the invoice details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 400, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    $v->isOK($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOK($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            //		$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity can't be zero or less. Product number: <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 16, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "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;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # insert purchase to DB
    db_conn("cubit");
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    if (!isset($vatcodes[$keys])) {
                        $vatcodes[$keys] = 0;
                    }
                    db_connect();
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    // 					if(pg_num_rows($Ri)<1) {
                    // 						return "Please select the vatcode for all your stock.";
                    // 					}
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    $vate = 'n';
                    if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $vate = 'y';
                    }
                    $vate = $vatcodes[$keys];
                    # insert purchase items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                }
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri) < 1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                db_connect();
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>| <input name='print' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$SUBTOT -= $taxex;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT + $taxex);
    	$SUBTOT += $taxex;
    
    	/* --- End Clac --- */
    $salespn = remval($salespn);
    if (!isset($bankid)) {
        if (isset($cusnum) and strlen($cusnum) > 0) {
            #get bankid from customer info
            $get_cbank = "SELECT bankid FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cbank = db_exec($get_cbank) or errDie("Unable to get bank information for customer.");
            if (pg_numrows($run_cbank) > 0) {
                $bankid = pg_fetch_result($run_cbank, 0, 0);
            } else {
                $bankid = "2";
            }
        } else {
            $bankid = "2";
        }
    }
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET salespn='{$salespn}', cusname = '{$cusname}', cusaddr = '{$cusaddr}', \n\t\t\tcusvatno = '{$cusvatno}', cordno = '{$cordno}', docref = '{$docref}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$odate}', terms = '{$terms}', \n\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}', bankid = '{$bankid}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($print)) {
        $OUTPUT = "<script>printer('nons-invoice-print.php?invid={$invid}');move('nons-invoice-new.php');</script>";
        require "template.php";
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        //$rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.$sql",SELF);
        # Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Non-Stock Invoices</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Invoices for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select a customer.</li>");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($cusnum)) {
        $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    if (isset($cordno)) {
        $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    }
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($rinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($rinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($rinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $rinv_year . "-" . $rinv_month . "-" . $rinv_day;
    if (!checkdate($rinv_month, $rinv_day, $rinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM rec_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $inv['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # 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'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM recinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    # remove old items
    $sql = "DELETE FROM recinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp,  div, vatcode, \n\t\t\t\t\t\t\tdescription, account\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', \n\t\t\t\t\t\t\t'{$descriptions[$keys]}', '{$accounts[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # Get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                $wtd = $whids[$keys];
                if (!isset($sernos[$keys])) {
                    $sernos[$keys] = "";
                }
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp, serno, div, \n\t\t\t\t\t\t\tvatcode\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    $i = 0;
    $Sl = "DELETE FROM invc WHERE inv='{$invid}'";
    $Rl = db_exec($Sl);
    while ($data = pg_fetch_array($Ri)) {
        if ($ct[$data['ccid']] > 0) {
            $Sl = "INSERT INTO invc (cid,inv,amount) VALUES ('{$data['ccid']}','{$invid}','" . $ct[$data['ccid']] . "')";
            $Rl = db_exec($Sl);
        }
        $i++;
    }
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE rec_invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}',\n\t\t\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', \n\t\t\t\tcomm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (strlen($bar) > 0) {
        $Sl = "SELECT * FROM possets WHERE div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_numrows($Rs) < 1) {
            return details($_POST, "<a href='pos-set.php'>Please set the point of sale setting by clicking here.</a>");
        }
        $Dets = pg_fetch_array($Rs);
        if ($Dets['opt'] == "No") {
            switch (substr($bar, strlen($bar) - 1, 1)) {
                case "0":
                    $tab = "ss0";
                    break;
                case "1":
                    $tab = "ss1";
                    break;
                case "2":
                    $tab = "ss2";
                    break;
                case "3":
                    $tab = "ss3";
                    break;
                case "4":
                    $tab = "ss4";
                    break;
                case "5":
                    $tab = "ss5";
                    break;
                case "6":
                    $tab = "ss6";
                    break;
                case "7":
                    $tab = "ss7";
                    break;
                case "8":
                    $tab = "ss8";
                    break;
                case "9":
                    $tab = "ss9";
                    break;
                default:
                    return details($_POST, "The code you selected is invalid");
            }
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "UPDATE " . $tab . " SET active = 'no' WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}',  '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Recurring Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Recurring Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("rec-invoice-view.php", "View Recurring Invoices"), ql("customers-new.php", "New Customer"));
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function report($_POST)
{
    extract($_POST);
    $date = $year . "-" . $mon . "-" . $day;
    $amount += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($user, "string", 1, 50, "Invalid user.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid order date.");
    }
    $met = remval($met);
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>{$e['msg']}</li>";
        }
        return $confirm;
    }
    if ($user != "0") {
        $whe = " AND by='{$user}'";
    } else {
        $whe = "";
    }
    if ($met != "all") {
        $whe .= " AND method='{$met}'";
    } else {
        $whe .= "";
    }
    db_conn("cubit");
    $sql = "SELECT * FROM payrec WHERE date='{$date}' {$whe}";
    $rslt = db_exec($sql) or errDie("Unable to retrieve pos report from Cubit.");
    $cash = $cheque = $credit_card = $credit = $sales = 0;
    while ($rec_data = pg_fetch_array($rslt)) {
        switch (strtolower($rec_data["method"])) {
            case "cash":
                $cash += $rec_data["amount"];
                break;
            case "cheque":
                $cheque += $rec_data["amount"];
                break;
            case "credit card":
                $credit_card += $rec_data["amount"];
                break;
            case "credit":
                $credit += $rec_data["amount"];
                break;
        }
        $sales += $rec_data["amount"];
    }
    db_conn('cubit');
    $Sl = "SELECT sum(amount) FROM payrec WHERE date='{$date}' {$whe}";
    $Ry = db_exec($Sl) or errDie("Unable to get pos rec.");
    $data = pg_fetch_array($Ry);
    $amount = sprint($amount);
    $expected = sprint($amount + $sales);
    $Report = "<h3>POS Report: {$date}</h3>\n\t<table " . TMPL_tblDflts . " style='width: 100%'>\n\t<tr>\n\t\t<th colspan=2>Report</th>\n\t</tr>\n\t<tr class='bg-odd'>\n\t\t<td>Starting Amount</td>\n\t\t<td align='right'>" . CUR . " {$amount}</td>\n\t</tr>\n\t<tr class='bg-even'>\n\t\t<td>Cash</td>\n\t\t<td align='right'>" . sprint($cash) . "</td>\n\t</tr>\n\t<tr class='bg-odd'>\n\t\t<td>Cheque</td>\n\t\t<td align='right'>" . sprint($cheque) . "</td>\n\t</tr>\n\t<tr class='bg-even'>\n\t\t<td>Credit Card</td>\n\t\t<td align='right'>" . sprint($credit_card) . "</td>\n\t</tr>\n\t<tr class='bg-odd'>\n\t\t<td>Credit</td>\n\t\t<td align='right'>" . sprint($credit) . "</td>\n\t</td>\n\t<tr class='bg-even'>\n\t\t<td>Expected Amount</td>\n\t\t<td align='right'>" . CUR . " {$expected}</td>\n\t</tr>\n\t</table>";
    include "temp.xls.php";
    Stream("Report", $Report);
    return $Report;
}
function slct($_GET)
{
    # Get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (isset($letters)) {
        $letters = remval($letters);
        $whe = "AND lower(surname) LIKE lower('%{$letters}%')";
    } else {
        $letters = "";
        $whe = "";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM nons_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 ($inv['ctyp'] == 's') {
        $VARS['invid'] = $invid;
        $VARS['ctyp'] = 's';
        $VARS['cusnum'] = $inv['tval'];
        return cdetails($VARS);
    } elseif ($inv['ctyp'] == 'c') {
        $VARS['invid'] = $invid;
        $VARS['ctyp'] = 'c';
        $VARS['deptid'] = $inv['tval'];
        return cdetails($VARS);
    } elseif ($inv['ctyp'] == 'cb') {
        $VARS['invid'] = $invid;
        $VARS['ctyp'] = 'cb';
        $VARS['deptid'] = 0;
        return cdetails($VARS);
    } elseif ($inv['ctyp'] == 'ac') {
        $VARS['invid'] = $invid;
        $VARS['ctyp'] = 'ac';
        $VARS['deptid'] = $inv['tval'];
        return acdetails($VARS);
    }
    db_connect();
    $sql = "SELECT * FROM customers WHERE div = '" . USER_DIV . "' {$whe} ORDER BY cusnum ASC";
    $cusRslt = db_exec($sql) or errDie("Could not retrieve Customers Information from the Database.", SELF);
    if (pg_numrows($cusRslt) < 1) {
        $custs = "No customers\r\n\t\t<input type='hidden' name='cusnum' value='#'>";
    } else {
        $custs = "<select name='cusnum'>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $custs .= "<option value='{$cus['cusnum']}'>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $custs .= "</select>";
    }
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
    $deptRslt = db_exec($sql);
    $depts = "<select name='deptid'>";
    if (pg_numrows($deptRslt) < 1) {
        $depts .= "<option value='-S'></option>";
    }
    while ($dept = pg_fetch_array($deptRslt)) {
        $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
    }
    $depts .= "</select>";
    $details = "\r\n\t\t\t\t\t<center>\r\n\t\t\t\t\t<h3>Print Non-Stock Invoices</h3>\r\n\t\t\t\t\t<h4>Customer Details</h4>\r\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t\t\t\t\t\t<input type='hidden' name='key' value='slct'>\r\n\t\t\t\t\t\t<input type='hidden' name='invid' value='{$invid}'>\r\n\t\t\t\t\t\t<input type='hidden' name='starting' value=''>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'> Invoice Details </th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Select when selling non stock goods to your customers") . ">\r\n\t\t\t\t\t\t\t<td><input type='radio' name='ctyp' value='s' checked='yes'> Select Customer</td>\r\n\t\t\t\t\t\t\t<td>{$custs}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Select when the sale of non stock goods is a cash sale") . ">\r\n\t\t\t\t\t\t\t<td><input type='radio' name='ctyp' value='c'>Cash Sale</td>\r\n\t\t\t\t\t\t\t<td>{$depts}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Select when the sale of non stock goods is not a cash sale") . ">\r\n\t\t\t\t\t\t\t<td><input type='radio' name='ctyp' value='ac'>Ledger Accounts Sale</td>\r\n\t\t\t\t\t\t\t<td></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'>Search by surname</th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td><input type='text' size='10' name='letters' value='{$letters}'></td>\r\n\t\t\t\t\t\t\t<td><input type='submit' value='Search &raquo;'></td>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td></td>\r\n\t\t\t\t\t\t\t<td align='center'><input type='submit' value='Continue &raquo;' name='button'></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t\t</form>";
    return $details;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($Cancel)) {
        db_connect();
        $Sl = "DELETE FROM corders WHERE sordid='{$sordid}' AND cusnum='0' AND div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to delete Consignment Order information");
        $sordid--;
        $Sql = "SELECT setval('corders_sordid_seq', '{$sordid}')";
        $Rslt = db_exec($Sql) or errDie("Unable to set Consignment id.");
        header("Location: main.php");
    }
    if (!isset($cusnum)) {
        return details($_POST, "");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($sordid, "num", 1, 20, "Invalid Consignment Order Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($cord_day, "num", 1, 2, "Invalid Consignment Order Date day.");
    $v->isOk($cord_month, "num", 1, 2, "Invalid Consignment Order Date month.");
    $v->isOk($cord_year, "num", 1, 5, "Invalid Consignment Order Date year.");
    $odate = $cord_year . "-" . $cord_month . "-" . $cord_day;
    if (!checkdate($cord_month, $cord_day, $cord_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Consignment Order Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid  Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Consignment Order info
    db_connect();
    $sql = "SELECT * FROM corders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Consignment Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li>- Consignment Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    $sord['chrgvat'] = $chrgvat;
    # check if Consignment Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Consignment Order number <b>{$sordid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM sord_data WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $sord['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($sord['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$sord['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert Consignment Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get selected stock in this Consignment Order
    db_connect();
    $sql = "SELECT * FROM corders_items  WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    # remove old items
    $sql = "DELETE FROM corders_items WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $sord['chrgvat'], $excluding, $sord['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\tINSERT INTO corders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tamt, disc, discp, div, vatcode, \n\t\t\t\t\t\tdescription, account\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', \n\t\t\t\t\t\t'{$descriptions[$keys]}', '{$accounts[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $sord['chrgvat'], $excluding, $sord['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                $wtd = $whids[$keys];
                # insert Consignment Order items
                $sql = "\n\t\t\t\t\tINSERT INTO corders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tamt, disc, discp, div, vatcode\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "','{$vatcodes[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Consignment Order items to Cubit.", SELF);
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $taxex += $delchrg;
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $sord['chrgvat'], $excluding, $sord['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    # insert Consignment Order to DB
    $sql = "\n\t\tUPDATE corders \n\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', \n\t\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', \n\t\t\tvat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', discount='{$traddiscmt}', \n\t\t\tdelivery='{$delexvat}' \n\t\tWHERE sordid = '{$sordid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM cord_data WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\tINSERT INTO cord_data (\n\t\t\tsordid, dept, customer, addr1, div\n\t\t) VALUES (\n\t\t\t'{$sordid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Consignment Order data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($donePrnt)) {
        $sql = "UPDATE corders SET done='y' WHERE sordid='{$sordid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Consignment Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('corder-print.php?sordid={$sordid}');\n\t\t\t\tmove('corder-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($doneBtn)) {
        # insert Consignment Order to DB
        $sql = "UPDATE corders SET done = 'y' WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Consignment Order status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Consignment Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Consignment Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='corder-print.php?sordid={$sordid}'>Print</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
        return $write;
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Consignment Order Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Consignment Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='corder-view.php'>View Consignment Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function printInv($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
    # mix dates
    $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    if (!checkdate($from_month, $from_day, $from_year)) {
        $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
    }
    if (!checkdate($to_month, $to_day, $to_year)) {
        $v->isOk($todate, "num", 1, 1, "Invalid to 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;
    }
    $accnum = remval($accnum);
    if (strlen($accnum) > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE lower(accno)=lower('{$accnum}')";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>Invalid account number</li>" . slct();
        }
        $cd = pg_fetch_array($Ri);
        $cusnum = $cd['cusnum'];
    }
    $rfromdate = ext_rdate($fromdate);
    $rtodate = ext_rdate($todate);
    # Set up table to display in
    $printInv = "\n\t\t<h3>View Recurring invoices. Date Range {$rfromdate} to {$rtodate}</h3>\n\t\t<form action='rec-invoice-proc.php' method='GET'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>Sales Person</th>\n\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    if (isset($all)) {
        $sql = "\n\t\t\tSELECT * FROM rec_invoices \n\t\t\tWHERE odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY surname";
    } else {
        $sql = "\n\t\t\tSELECT * FROM rec_invoices \n\t\t\tWHERE odate >= '{$fromdate}' AND odate <= '{$todate}' AND cusnum = {$cusnum} AND div = '" . USER_DIV . "' ORDER BY surname";
    }
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'>No Recurring Invoices found for the selected customer.</li><br>";
    } else {
        $counter = 0;
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            # Format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if (isset($selnum) and $counter < 1000) {
                $ch = "checked";
            } else {
                if (isset($f)) {
                    $ch = "checked";
                } else {
                    $ch = "";
                }
            }
            $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['salespn']}</td>\n\t\t\t\t\t<td>RI {$inv['invid']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$inv['total']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='invids[]' value='{$inv['invid']}' {$ch}></td>\n\t\t\t\t\t<td><a href='rec-invoice-details.php?invid={$inv['invid']}'>Details</a></td>\n\t\t\t\t\t<td><a href='rec-invoice-new.php?invid={$inv['invid']}&cont=1&letters='>Edit</a></td>\n\t\t\t\t\t<td><a href='rec-invoice-run.php?invid={$inv['invid']}'>Invoice</a></td>\n\t\t\t\t\t<td><a href='rec-invoice-rem.php?invid={$inv['invid']}'>Remove</a></td>\n\t\t\t\t</tr>";
            $i++;
            $counter++;
        }
    }
    if ($i > 0) {
        $tot1 = sprint($tot1);
        $printInv .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'>Totals:{$i}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot1}</td>\n\t\t\t\t<td><br></td>\n\t\t\t\t<td colspan='10'><input type='submit' name='edit' value='Edit Item Prices On Selected'> <input type='submit' value='Process Selected' name='proc'></td>\n\t\t\t</tr>";
        $printInv .= "\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t</form>\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t\t\t\t<input type='hidden' name='accnum' value='{$accnum}'>\n\t\t\t\t<input type='hidden' name='cusnum' value='{$cusnum}'>\n\t\t\t\t<input type='hidden' name='all' value=''>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='6'></td>\n\t\t\t\t\t<td align='right'></td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t\t<td colspan='10'><input type='submit' value='Select All' name='f'> &nbsp; <input type='submit' value='Select 1000' name='selnum'></td>\n\t\t\t\t</tr>\n\t\t\t</form>";
    }
    $printInv .= "</table>" . mkQuickLinks(ql("rec-invoice-new.php", "New Recurring Invoice"), ql("customers-new.php", "New Customer"));
    return $printInv;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    $delvat += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (isset($printdel)) {
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('Delivery Note','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($branch, "num", 1, 20, "Invalid Branch, Please select a branch.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 1024, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($inv_date_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($inv_date_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($inv_date_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $inv_date_year . "-" . $inv_date_month . "-" . $inv_date_day;
    if (!checkdate($inv_date_month, $inv_date_day, $inv_date_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        $tmp_sernos = $sernos;
        // only check for uniqueness among items not selected for removal
        foreach ($sernos as $k => $serno_val) {
            if (isset($remprod) && in_array($k, $remprod)) {
                unset($tmp_sernos[$k]);
            }
        }
        if (!ext_isUnique(ext_remBlnk($tmp_sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serai no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    if (!isset($qtys) && isset($qtemp)) {
        $qtys[] = $qtemp;
    } elseif (isset($qtys) && isset($qtemp)) {
        //array_unshift ($qtys,$qtemp);
        $qtys[] = $qtemp;
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # 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>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    if ($cusnum != $inv['cusnum'] or $branch != $inv['branch']) {
        $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) {
            #no branch addres ? since we NEED to update the address, add the customer's here
            $get_cadd = "SELECT del_addr1 FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cadd = db_exec($get_cadd) or errDie("Unable to get customer delivery address");
            if (pg_numrows($run_cadd) < 1) {
                #no customer ??
                return details($_POST, "<li class='err'>Invalid customer selected.</li>");
            } else {
                $carr = pg_fetch_array($run_cadd);
                $update_addr = "UPDATE invoices SET del_addr  = '{$carr['del_addr1']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        } 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 . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        }
    }
    # 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 selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $inv['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # 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'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $newvat = 0;
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                $amt[$keys] = 0;
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, serno, div, vatcode, description, \n\t\t\t\t\t\t\taccount, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t'{$accounts[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # Get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, ss, serno, div, \n\t\t\t\t\t\t\tvatcode, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                if (strlen($sernos[$keys]) > 0) {
                    ext_resvSer($sernos[$keys], $stk['stkid']);
                }
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "\t| <input name='doneBtn' type='submit' value='Process'>";
            //if ($cust["email"] != "") {
            $_POST["done"] .= " | <input name='emailBtn' type='submit' value='Process and Email to Customer'>";
            //}
        }
    } else {
        $_POST["done"] = "";
    }
    //$newvat+=vatcalc($delchrg,$chrgvat,"no",$traddisc);
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    #get traddisc setting ...
    $traddisc_setting = getCSetting("SET_INV_TRADDISC");
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    ----------------------OLD----------------------
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    */
    #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'];
        }
    }
    // Delivery Date
    $deldate = "{$del_date_year}-{$del_date_month}-{$del_date_day}";
    /* --- ----------- Clac --------------------- */
    if (!isset($bankid)) {
        $bankid = cust_bank_id($cusnum);
    }
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}', \n\t\t\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', \n\t\t\t\tcomm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}', branch = '{$branch}', \n\t\t\t\tdeldate = '{$deldate}', bankid = '{$bankid}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO inv_items (\n\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, serno, \n\t\t\t\tdiv, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}', '{$s['selamt']}','0','0','{$bar}', '{$serno_bar}', \n\t\t\t\t'" . USER_DIV . "', (SELECT id FROM cubit.vatcodes LIMIT 1)\n\t\t\t)";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn) || isset($emailBtn)) {
        # Check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        # Insert quote to DB
        $sql = "UPDATE invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if (isset($emailBtn)) {
            $email = "email=true";
        } else {
            $email = "";
        }
        if ($data['value'] == "Yes") {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tnhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&salespn={$salespn}&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        } else {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        }
        # Print the invoice
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved. To view it go to 'View incomplete invoices'</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($code, "string", 1, 255, "Invalid code.");
    $v->isOk($description, "string", 1, 255, "Invalid description.");
    $v->isOk($id, "num", 1, 50, "Invalid id.");
    $v->isOk($vat_amount, "float", 1, 255, "Invalid VAT percentage.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    $zero = remval($zero);
    # connect to db
    db_connect();
    # write to db
    $sql = "UPDATE vatcodes SET code = '{$code}', description = '{$description}', zero='{$zero}', vat_amount = '{$vat_amount}' WHERE id = '{$id}'";
    $clasRslt = db_exec($sql) or errDie("Unable to edit classification on system.", SELF);
    if (pg_cmdtuples($clasRslt) < 1) {
        return "<li class=err>Unable to edit vat code.";
    }
    $write = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t<tr><th>VAT Code edited</th></tr>\r\n\t<tr class=datacell><td>VAT Code <b>{$code}</b>, has been edited.</td></tr>\r\n\t</table>\r\n\t<p>\r\n\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t<tr><th>Quick Links</th></tr>\r\n\t<tr class='bg-odd'><td><a href='vatcodes-view.php'>View VAT Codes</a></td></tr>\r\n\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $write;
}
function report($_POST)
{
    extract($_POST);
    if (!isset($name)) {
        $name = "";
    }
    if (!isset($subject)) {
        $subject = "";
    }
    if (!isset($notes)) {
        $notes = "";
    }
    $name = remval($name);
    $subject = remval($subject);
    $notes = remval($notes);
    $whe = "";
    $csc = 0;
    if (!isset($team)) {
        $team = 0;
        $user = 0;
        $cat = 0;
        $csc = 0;
    } else {
        $team += 0;
        $user += 0;
        $cat += 0;
        $csc += 0;
    }
    if ($team != 0) {
        $whe .= " AND teamid='{$team}' ";
    }
    if ($user != 0) {
        $whe .= " AND userid='{$user}' ";
    }
    if ($cat != 0) {
        $whe .= " AND catid='{$cat}' ";
    }
    if ($csc != 0) {
        if ($csc == 1) {
            $whe .= " AND csct='Contact' ";
        } elseif ($csc == 2) {
            $whe .= " AND csct='Customer' ";
        } elseif ($csc == 3) {
            $whe .= " AND csct='Supplier' ";
        }
    }
    if (strlen($name) > 0) {
        $whe .= " AND lower(name) LIKE lower('%{$name}%') ";
    }
    if (strlen($subject) > 0) {
        $whe .= " AND lower(sub) LIKE lower('%{$subject}%') ";
    }
    if (strlen($notes) > 0) {
        $whe .= " AND lower(notes) LIKE lower('%{$notes}%') ";
    }
    $date = date("Y-m-d");
    db_conn('crm');
    $Sl = "SELECT * FROM crms WHERE userid='" . USER_ID . "'";
    $Ry = db_exec($Sl) or errDie("Unable to get info from db.");
    if (pg_numrows($Ry) < 1) {
        return "\r\n\t\t\tYou have not been set up to use query management.<br>\r\n\t\t\tPlease allocate yourself to a team.\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='crms-allocate.php'>Allocate users to Teams</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='index.php'>My Business</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    $crmdata = pg_fetch_array($Ry);
    $Sl = "SELECT * FROM teams WHERE id='{$crmdata['teamid']}'";
    $Ry = db_exec($Sl) or errDie("Unable to get team data.");
    $teamdata = pg_fetch_array($Ry);
    $username = USER_NAME;
    $disdate = date("d-m-Y, l, G:i");
    $i = 0;
    $out = "";
    $Sl = "SELECT id,tid,name,username,sub,closedate,opendate FROM closedtokens WHERE 1=1 {$whe} ORDER BY id";
    $Ry = db_exec($Sl) or errDie("Unable to get data from system.");
    if (pg_numrows($Ry) > 0) {
        $i = 0;
        $out = "\r\n\t\t\t<h3>Closed Queries</h3>\r\n\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>No.</th>\r\n\t\t\t\t\t<th>Subject</th>\r\n\t\t\t\t\t<th>User</th>\r\n\t\t\t\t\t<th>Date Opened</th>\r\n\t\t\t\t\t<th>Date Closed</th>\r\n\t\t\t\t\t<th>Options</th>\r\n\t\t\t\t</tr>";
        while ($data = pg_fetch_array($Ry)) {
            $i++;
            $out .= "\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>{$data['tid']}</td>\r\n\t\t\t\t\t<td>{$data['name']} - {$data['sub']}</td>\r\n\t\t\t\t\t<td>{$data['username']}</td>\r\n\t\t\t\t\t<td>{$data['opendate']}</td>\r\n\t\t\t\t\t<td>{$data['closedate']}</td>\r\n\t\t\t\t\t<td><a href='tokens-closed-details.php?id={$data['id']}'>View Details</a></td>\r\n\t\t\t\t</tr>";
        }
        $out .= "</table>";
    } else {
        $out = "There are no closed queries for the selected criteria.";
    }
    $out .= "\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='index.php'>My Business</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $out;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class=err>" . $e["msg"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $td = $date;
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($suppRslt) < 1) {
        return "<li> Invalid Supplier ID.";
    } else {
        $supp = pg_fetch_array($suppRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class=err>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    # update all supplies xchange rate first
    xrate_update($supp['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($supp['fcid'], $rate);
    $supp['supname'] = remval($supp['supname']);
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['credacc'], $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td><td>{$supp['supno']} - {$supp['supname']}</td></tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordCT(-$amount, $supp['supid']);
        frecordCT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$supp['supno']} - {$supp['supname']}</td><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td></tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordDT($amount, $supp['supid']);
        frecordDT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $edate = date("Y-m-d");
    # record the payment on the statement
    $sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$supp['supid']}', '{$td}', '0', '{$accid}', '{$details}', '{$sfamt}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$samount}'),fbalance = (fbalance + '{$sfamt}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Ledger Records
    suppledger($supp['supid'], $accid, $td, $refnum, $details, $amount, $type);
    db_connect();
    // Start layout
    $write = "<h3>Journal transaction has been recorded</h3>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n\t\t{$tran}\n\t\t<tr><td><br></td></tr>\n\t\t<tr colspan=2><td><h4>Amount</h4></td></tr>\n\t\t<tr class='bg-even'><td colspan=2><b>" . CUR . " {$famt}</b></td></tr>\n\t</table>\n\t<P>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../supp-view.php'>View Suppliers</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write_data($_POST)
{
    $date = date("Y-m-d");
    # get vars
    extract($_POST);
    if (isset($back)) {
        return get_data("");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($accountname, "string", 0, 100, "Account");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 250, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 250, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($website, "string", 0, 255, "Website");
    $v->isOk($religion, "string", 0, 100, "Religion");
    $v->isOk($race, "string", 0, 100, "Race");
    $v->isOk($gender, "string", 0, 6, "Gender");
    $v->isOk($salespn, "num", 1, 9, "Sales person.");
    $v->isOK($team_id, "num", 1, 9, "Team.");
    if (!empty($ncdate_day) || !empty($ncdate_month) || !empty($ncdate_year)) {
        $v->isOk($ncdate_day, "num", 1, 2, "Next contact date (Day)");
        $v->isOk($ncdate_month, "num", 1, 2, "Next contact day (Month)");
        $v->isOk($ncdate_year, "num", 4, 4, "Next contact day (Year)");
        $ncdate_col = ", ncdate";
        $ncdate = ", '{$ncdate_year}-{$ncdate_month}-{$ncdate_day}'";
    } else {
        $ncdate_col = "";
        $ncdate = "";
    }
    $v->isOk($Con, "string", 2, 3, "Invalid private.");
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    $assigned_to = USER_NAME;
    $assigned_to_id = USER_ID;
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($err);
    }
    db_conn('cubit');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add lead to database. (TB)</li>";
    }
    if (isset($supacc)) {
        $supacc = remval($supacc);
        $sql = "\r\n\t\t\tINSERT INTO  suppliers (\r\n\t\t\t\tdeptid, supno, supname, location, fcid, currency, vatnum, supaddr, contname, tel, fax, \r\n\t\t\t\temail, url, listid, bankname, branname, brancode, bankaccno, balance, fbalance, div\r\n\t\t\t) VALUES (\r\n\t\t\t\t'2', '{$supacc}', '{$surname}', 'loc', '2', 'R', '', '{$hadd} \n {$padd}', '', '{$tell}', '{$fax}', \r\n\t\t\t\t'{$email}', '', '2', '', '', '', '', 0, 0, '" . USER_DIV . "'\r\n\t\t\t)";
        $supRslt = db_exec($sql) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_cmdtuples($supRslt) < 1) {
            return "<li class='err'>Unable to add supplier to database.</li>";
        }
        if (($supp_id = pglib_lastid("suppliers", "supid")) == 0) {
            return "<li class='err'>Unable to add supplier to lead list.</li>";
        }
        $accountname = $surname;
        $account_type = "Supplier";
        $account_id = $supp_id;
    } else {
        $supp_id = 0;
    }
    if (isset($cusacc)) {
        $cusacc = remval($cusacc);
        $sql = "\r\n\t\t\tINSERT INTO customers (\r\n\t\t\t\tdeptid, accno, surname, title, init, location, fcid, currency, category, class, addr1, paddr1, vatnum, \r\n\t\t\t\tcontname, bustel, tel, cellno, fax, email, url, traddisc, setdisc, pricelist, chrgint, overdue, \r\n\t\t\t\tintrate, chrgvat, credterm, odate, credlimit, blocked, balance, div,deptname,classname,catname\r\n\t\t\t) VALUES (\r\n\t\t\t\t'2', '{$cusacc}', '{$surname}', '', '', 'loc', '2', 'R', '2', '2', '{$hadd}', '{$padd}', '', \r\n\t\t\t\t'', '', '{$tell}', '{$cell}', '{$fax}', '{$email}', '', '0', '0', '2', 'yes', '0', '0', 'yes', \r\n\t\t\t\t'0', '{$date}', '0', 'no', '0', '" . USER_DIV . "','Ledger 1','General','General'\r\n\t\t\t)";
        $custRslt = db_exec($sql) or errDie("Unable to add customer to system.", SELF);
        if (pg_cmdtuples($custRslt) < 1) {
            return "<li class='err'>Unable to add customer to database.";
        }
        if (($cust_id = pglib_lastid("customers", "cusnum")) == 0) {
            return "<li class='err'>Unable to add customer to lead list.</li>";
        }
        $accountname = $surname;
        $account_type = "Customer";
        $account_id = $cust_id;
    } else {
        $cust_id = 0;
    }
    # write to db
    db_conn("crm");
    $sql = "\r\n\t\tINSERT INTO leads (\r\n\t\t\tsurname, name, accountname, account_id, account_type, lead_source, title, department, \r\n\t\t\tbirthdate, tell, cell, fax, tell_office, tell_other, email, email_other, assistant, \r\n\t\t\tassistant_phone, padd, padd_city, padd_state, padd_code, padd_country, hadd, hadd_city, \r\n\t\t\thadd_state, hadd_code, hadd_country, description, website, religion, race, gender, \r\n\t\t\tref, date, con, by, div, supp_id, cust_id, assigned_to, \r\n\t\t\tassigned_to_id {$ncdate_col}, salespid, team_id\r\n\t\t) VALUES (\r\n\t\t\t'{$surname}', '{$name}', '{$accountname}', '{$account_id}', '{$account_type}', '{$lead_source}', '{$title}', '{$department}', \r\n\t\t\t'{$birthdate}', '{$tell}', '{$cell}', '{$fax}', '{$tell_office}', '{$tell_other}', '{$email}', '{$email_other}', '{$assistant}', \r\n\t\t\t'{$assistant_phone}', '{$padd}', '{$padd_city}', '{$padd_state}', '{$padd_code}', '{$padd_country}', '{$hadd}', '{$hadd_city}', \r\n\t\t\t'{$hadd_state}', '{$hadd_code}', '{$hadd_country}', '{$description}', '{$website}', '{$religion}', '{$race}', '{$gender}', \r\n\t\t\t'', CURRENT_DATE, '{$Con}', '" . USER_NAME . "', '" . USER_DIV . "', '{$supp_id}', '{$cust_id}', '{$assigned_to}', \r\n\t\t\t'{$assigned_to_id}' {$ncdate}, '{$salespn}', '{$team_id}'\r\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
    $lead_id = pglib_lastid("leads", "id");
    // Add entry to today
    if (!empty($ncdate_year) && !empty($ncdate_month) && !empty($ncdate_day)) {
        $contact_date = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
        addTodayEntry("Leads", $lead_id, $contact_date, "Contact {$surname}");
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add lead to database. (TC)</li>";
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$surname}");
        exit;
    }
    $write_data = "\r\n\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Lead added</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='datacell'>\r\n\t\t\t\t<td>{$surname} has been added to Cubit.</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='" . SELF . "'>Add another lead</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../crmsystem/leads_list.php'>View Leads</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write_data;
}
function settings($_POST)
{
    extract($_POST);
    db_conn('cubit');
    $err = "";
    $save = false;
    if (isset($account)) {
        $save = true;
        $account = remval($account);
        $Sl = "SELECT * FROM statement_settings";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO statement_settings (ad) VALUES ('{$account}')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE statement_settings SET ad='{$account}'";
            $Ri = db_exec($Sl);
        }
    }
    $Sl = "SELECT * FROM statement_settings";
    $Ri = db_exec($Sl);
    $sd = pg_fetch_array($Ri);
    if (!$save) {
        $ex = "<li class='err'>Please select your statement import settings & then click 'Update'</li>";
    } else {
        $ex = "<li class='err'>Statement import settings saved</li>";
    }
    if ($sd['ad'] == "num") {
        $sel1 = "";
        $sel2 = "selected";
    } else {
        $sel1 = "";
        $sel2 = "";
    }
    $accounts = "\r\n\t\t<select name='account'>\r\n\t\t\t<option value='name' {$sel1}>Account Name</option>\r\n\t\t\t<option value='num' {$sel2}>Account Number</option>\r\n\t\t</select>";
    db_conn('cubit');
    $Sl = "SELECT * FROM statement_refs ORDER BY ref";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $tab = "\r\n\t\t<h4>The following are descriptions on your statement which cubit will try to detect.</h4>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Description</th>\r\n\t\t\t\t<th>+-</th>\r\n\t\t\t\t<th>Type</th>\r\n\t\t\t\t<th>Action</th>\r\n\t\t\t\t<th>Contra Account/Action Details</th>\r\n\t\t\t\t<th colspan='2'>Options</th>\r\n\t\t\t</tr>";
    $i = 0;
    while ($rd = pg_fetch_array($Ri)) {
        if ($rd['action'] == "c" || $rd['action'] == "cr") {
            db_conn('core');
            $rd['account'] += 0;
            $Sl = "SELECT * FROM accounts WHERE accid='{$rd['account']}'";
            $Rl = db_exec($Sl) or errDie("Unable to get account.");
            $ad = pg_fetch_array($Rl);
            $details = $ad['accname'];
            $action = "Insert into cashbook";
        } elseif ($rd['action'] == "cp") {
            db_conn('cubit');
            $Sl = "SELECT cusnum,surname FROM customers WHERE cusnum='{$rd['account']}'";
            $Rl = db_exec($Sl) or errDie("Unable to get customers.");
            $cd = pg_fetch_array($Rl);
            $details = $cd['surname'];
            $action = "Customer Payment";
        } elseif ($rd['action'] == "sp") {
            db_conn('cubit');
            $Sl = "SELECT supid,supname FROM suppliers WHERE supid='{$rd['account']}'";
            $Rl = db_exec($Sl) or errDie("Unable to get suppliers.");
            $cd = pg_fetch_array($Rl);
            $details = $cd['supname'];
            $action = "Supplier Payment";
        } elseif ($rd['action'] == "Ignore") {
            $details = "";
            $action = "Ignore";
        } elseif ($rd['action'] == "Delete") {
            $details = "";
            $action = "Delete";
        }
        $tab .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$rd['ref']}</td>\r\n\t\t\t\t<td>{$rd['pn']}</td>\r\n\t\t\t\t<td>{$rd['dets']}</td>\r\n\t\t\t\t<td>{$action}</td>\r\n\t\t\t\t<td>{$details}</td>\r\n\t\t\t\t<td><a href='statement-ref-edit.php?id={$rd['id']}'>Edit</a></td>\r\n\t\t\t\t<td><a href='statement-ref-rem.php?id={$rd['id']}'>Delete</a></td>\r\n\t\t\t</tr>";
        $i++;
    }
    $tab .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td colspan='7' align='center'><a href='statement-ref-add.php'>ADD NEW</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    $out = "\r\n\t\t<h3>Statement Import Settings</h3>\r\n\t\t{$ex}\r\n\t\t{$err}\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t<form action='" . SELF . "' method='POST'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>Settings</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>Choose Account By</td>\r\n\t\t\t\t<td>{$accounts}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Update &raquo;'></td>\r\n\t\t\t</tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t<br>\r\n\t\t{$tab}\r\n\t\t<br>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='statement-ref-add.php'>Add new description</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $out;
}
function printCat($_POST)
{
    extract($_POST);
    global $user_admin;
    $typeid = remval($typeid);
    # Set up table to display in
    $printCat = "\r\n    <h3>Documents</h3>\r\n    <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n    <tr><th>Type</th><th>Ref</th><th>Document</th><th>Date</th><th>Description</th><th>Filename</th><th colspan=3>Options</th></tr>";
    if ($typeid != '0') {
        $whe = "AND typeid='{$typeid}' ";
    } else {
        $whe = "";
    }
    // Check if user is admin
    db_conn("cubit");
    $sql = "SELECT admin FROM users WHERE userid='" . USER_ID . "'";
    $admRslt = db_exec($sql) or errDie("Unable to retrieve user admin status from Cubit.");
    $admin = pg_fetch_result($admRslt, 0);
    if (!$admin) {
        $adm = "AND docaccess='Yes'";
    } else {
        $adm = "";
    }
    # Connect to database
    //db_conn (YR_DB);
    db_conn("yr2");
    # Query server
    $i = 0;
    $sql = "SELECT * FROM documents WHERE div = '" . USER_DIV . "' {$whe} {$adm} ORDER BY docname ASC";
    $docRslt = db_exec($sql) or errDie("Unable to retrieve Documents from database.");
    if (pg_numrows($docRslt) < 1) {
        return "<li>There are no Documents in Cubit.</li>\r\n\t\t\t <p>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=15%>\r\n\t\t<tr><td><br></td></tr>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='doc-add.php'>Add Document</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='doc-view.php'>View Documents</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n\t\t</table>";
    }
    while ($doc = pg_fetch_array($docRslt)) {
        $printCat .= "<tr class='" . bg_class() . "'>\r\n\t\t\t<td>{$doc['typename']}</td>\r\n\t\t\t<td>{$doc['docref']}</td>\r\n\t\t\t<td>{$doc['docname']}</td>\r\n\t\t\t<td>{$doc['docdate']}</td>\r\n\t\t\t<td>{$doc['descrip']}</td>\r\n\t\t\t<td>{$doc['filename']}</td>\r\n\t\t\t<td><a href='doc-edit.php?docid={$doc['docid']}'>Edit</a></td>";
        $printCat .= "<td><a href='doc-dload.php?docid={$doc['docid']}'>Download</a></td>\r\n\t\t\t<td><a href='doc-rem.php?docid={$doc['docid']}'>Remove</a></td>\r\n\t\t</tr>";
        $i++;
    }
    $printCat .= "</table>\r\n    <p>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=15%>\r\n        <tr><td><br></td></tr>\r\n        <tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='doc-add.php'>Add Document</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='doc-view.php'>View Documents</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $printCat;
}
function write($_POST)
{
    extract($_POST);
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    if (isset($branch_addr)) {
        $v->isOk($branch_addr, "num", 1, 20, "Invalid site address.");
    } else {
        $branch_addr = 0;
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    //$v->isOk ($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    // 	$v->isOk ($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespid, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($subtot, "float", 0, 20, "Invalid subtotal.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($collection, "string", 0, 40, "Invalid collection method.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    if (isset($des)) {
        $des = remval($des);
    }
    if (isset($asset_id) && is_numeric($asset_id)) {
        foreach ($asset_id as $value) {
            $sql = "SELECT id, des FROM cubit.assets WHERE id='{$asset_id}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
            $asset_data = pg_fetch_array($asset_rslt);
            if (isHired($asset_id)) {
                $v->addError(0, "Asset " . getSerial($asset_id) . " {$asset_data['des']} has already been hired out.");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}<li>";
        }
        return details($_POST, $err);
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_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>- Invoice Not Found[1]</li>";
    // 	}
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = 0;
    # 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 = '{$deptid}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found[3]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    if (isset($upBtn) || isset($hirenewBtn)) {
        $update_ret = update($_POST);
    } else {
        $update_ret = false;
    }
    # begin updating
    pglib_transaction("BEGIN");
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}'";
    $stktRslt = db_exec($sql);
    $subtot = 0;
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        //$sql = "UPDATE stock SET alloc = (alloc - '$stkt[qty]')  WHERE stkid = '$stkt[stkid]' AND div = '".USER_DIV."'";
        //$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
        //if(strlen($stkt['serno']) > 0)
        //ext_unresvSer($stkt['serno'], $stkt['stkid']);
        $subtot += $stkt["amt"];
    }
    # remove old items
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $VATP = TAX_VAT;
    $subtotal = sprint($subtot + $delchrg);
    $traddiscmt = sprint($subtotal * $traddisc / 100);
    $subtotal = sprint($subtotal - $traddiscmt);
    $VAT = $subtotal / 100 * 14;
    $SUBTOT = $subtotal;
    $TOTAL = $subtotal + $VAT;
    $delexvat = sprint($delchrg);
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
            $cusname = "{$arr['cusname']} {$arr['surname']}";
        }
    } else {
        $cusacc = "";
        $cusname = "";
    }
    # insert invoice to DB
    $sql = "\r\n\t\t\tUPDATE hire.hire_invoices \r\n\t\t\tSET cusnum='{$cusnum}', cusname='{$cusname}', rounding='{$rounding}', deptid='{$deptid}', deptname='{$dept['deptname']}', \r\n\t\t\t\tcordno='{$cordno}', ordno='{$ordno}', salespn='{$salespid}', odate='{$odate}', traddisc='{$traddisc}', \r\n\t\t\t\tdelchrg='{$delchrg}', subtot='{$SUBTOT}', vat='{$VAT}',balance='{$TOTAL}', total='{$TOTAL}', discount='{$traddiscmt}', \r\n\t\t\t\tdelivery='{$delexvat}', vatnum='{$vatnum}', cusacc='{$cusacc}', telno='{$telno}', deposit_type='{$deposit_type}', \r\n\t\t\t\tdeposit_amt='{$deposit_amt}', collection='{$collection}', custom_txt='{$custom_txt}', branch_addr='{$branch_addr}' \r\n\t\t\tWHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    return details($_POST, $update_ret);
    if (strlen($bar) > 0) {
        $Sl = "SELECT * FROM possets WHERE div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_numrows($Rs) < 1) {
            return details($_POST, "Please go set the point of sale settings under the stock settings");
        }
        $Dets = pg_fetch_array($Rs);
        if ($Dets['opt'] == "No") {
            switch (substr($bar, strlen($bar) - 1, 1)) {
                case "0":
                    $tab = "ss0";
                    break;
                case "1":
                    $tab = "ss1";
                    break;
                case "2":
                    $tab = "ss2";
                    break;
                case "3":
                    $tab = "ss3";
                    break;
                case "4":
                    $tab = "ss4";
                    break;
                case "5":
                    $tab = "ss5";
                    break;
                case "6":
                    $tab = "ss6";
                    break;
                case "7":
                    $tab = "ss7";
                    break;
                case "8":
                    $tab = "ss8";
                    break;
                case "9":
                    $tab = "ss9";
                    break;
                default:
                    return details($_POST, "The code you selected is invalid");
            }
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            if (!($stid > 0)) {
                return details($_POST, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, whid, stkid, qty, amt, disc, discp, ss, serno, \r\n\t\t\t\t\tdiv\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '{$bar}', \r\n\t\t\t\t\t'" . USER_DIV . "'\r\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "UPDATE " . $tab . " SET active = 'no' WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "INSERT INTO hire.hire_invitems(invid, whid, stkid, qty, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}','0','0','{$bar}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM hire.hire_invitems WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.</li>";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\r\n\t\t\t(You can only overpay with cash)</li>");
        }
        // make plant available
        $sql = "UPDATE hire.hire_invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "<script>printer('pos-invoice-print.php?invid={$invid}');move('pos-invoice-new.php');</script>";
        require "template.php";
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\r\n\t\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>New Point of Sale Invoice Saved</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-new.php'>New Point of Sale Invoice</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($code, "string", 1, 255, "Invalid code.");
    $v->isOk($description, "string", 1, 255, "Invalid description.");
    $v->isOk($vat_amount, "float", 1, 255, "Invalid VAT percentage.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    $zero = remval($zero);
    # check stock code
    db_connect();
    $sql = "SELECT code FROM vatcodes WHERE lower(code) = lower('{$code}')";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class=err> A VAT Code with code : <b>{$code}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # connect to db
    db_connect();
    # write to db
    $sql = "INSERT INTO vatcodes(code, description,vat_amount,zero,del) VALUES ('{$code}', '{$description}','{$vat_amount}','{$zero}','No')";
    $catRslt = db_exec($sql) or errDie("Unable to add class to system.", SELF);
    if (pg_cmdtuples($catRslt) < 1) {
        return "<li class=err>Unable to add classname to database.";
    }
    $write = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t<tr><th>VAT Code added to system</th></tr>\r\n\t<tr class=datacell><td>New VAT code <b>{$code}</b>, has been successfully added to the system.</td></tr>\r\n\t</table>\r\n\t<p>\r\n\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t<tr><th>Quick Links</th></tr>\r\n\t<tr class='bg-odd'><td><a href='vatcodes-view.php'>View VAT Codes</a></td></tr>\r\n\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($quoid, "num", 1, 20, "Invalid Quote Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($quote_day, "num", 1, 2, "Invalid Quote Date day.");
    $v->isOk($quote_month, "num", 1, 2, "Invalid Quote Date month.");
    $v->isOk($quote_year, "num", 1, 5, "Invalid Quote Date year.");
    $odate = $quote_year . "-" . $quote_month . "-" . $quote_day;
    if (!checkdate($quote_month, $quote_day, $quote_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Quote Date.");
    }
    $v->isOk($ncdate_day, "num", 1, 2, "Invalid Next Contact Date day.");
    $v->isOk($ncdate_month, "num", 1, 2, "Invalid Next Contact Date month.");
    $v->isOk($ncdate_year, "num", 1, 5, "Invalid Next Contact Date year.");
    $ncdate = $ncdate_year . "-" . $ncdate_month . "-" . $ncdate_day;
    if (!checkdate($ncdate_month, $ncdate_day, $ncdate_year)) {
        $v->isOk($ncdate, "num", 1, 1, "Invalid Followon Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return details($_POST, $err);
    }
    // 	# insert quote to DB
    // 	$sql = "UPDATE quotes SET delvat='$delvat',cusnum = '$cusnum', deptname = '$dept[deptname]', cusacc = '$cust[accno]', cusname = '$cust[cusname]', surname = '$cust[surname]', cusaddr = '$cust[addr1]', cusvatno = '$cust[vatnum]', cordno = '$cordno', ordno = '$ordno', chrgvat = '$chrgvat', terms = '$terms', salespn = '$salespn',
    // 	odate = '$odate', traddisc = '$traddisc', delchrg = '$delchrg', subtot = '$SUBTOT', vat = '$VAT', total = '$TOTAL', balance = '$TOTAL', comm = '$comm', discount='$traddiscmt', delivery='$delexvat' WHERE quoid = '$quoid'";
    // 	$rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.",SELF);
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<li>- Quote Not Found</li>";
    }
    $quo = pg_fetch_array($quoRslt);
    $quo['traddisc'] = $traddisc;
    # check if quote has been printed
    if ($quo['accepted'] == "y") {
        $error = "<li class='err'>Error : Quote number <b>{$quoid}</b> has already been printed.</li>";
        $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 = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM quote_data WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $quo['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($quo['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$quo['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert quote to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this quote
    db_connect();
    $sql = "SELECT * FROM quote_items  WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    #while($stkt = pg_fetch_array($stktRslt)){
    #	update stock(alloc + qty)
    #	$sql = "UPDATE stock SET alloc = (alloc - '$stkt[qty]')  WHERE stkid = '$stkt[stkid]'";
    #	$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    #}
    # remove old items
    $sql = "DELETE FROM quote_items WHERE quoid='{$quoid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
                // 					if(in_array($keys, $remprod)){
                // 						# skip product (wonder if $keys still align)
                // 						$amt[$keys] = 0;
                // 						continue;
                // 					}else{
                // 						# get selamt from selected stock
                // 						$sql = "SELECT * FROM stock WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
                // 						$stkRslt = db_exec($sql);
                // 						$stk = pg_fetch_array($stkRslt);
                //
                // 						# Calculate the Discount discount
                // 						if($disc[$keys] < 1){
                // 							if($discp[$keys] > 0){
                // 								$disc[$keys] = (($discp[$keys]/100) * $unitcost[$keys]);
                // 							}
                // 						}else{
                // 							$discp[$keys] = (($disc[$keys] * 100) / $unitcost[$keys]);
                // 						}
                //
                // 						# Calculate amount
                // 						$amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                //
                // 						# Check Tax Excempt
                // 						if($stk['exvat'] == 'yes'){
                // 							$taxex += $amt[$keys];
                // 						}
                //
                // 						$wtd = $whids[$keys];
                // 						# insert quote items
                // 						$sql = "INSERT INTO quote_items(quoid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$quoid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', '$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')";
                // 						$rslt = db_exec($sql) or errDie("Unable to insert quote items to Cubit.",SELF);
                //
                // 						# update stock(alloc + qty)
                // 						# $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                // 						# $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
                // 					}
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $quo['chrgvat'], $excluding, $quo['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $vatcodes[$keys] += 0;
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO quote_items (\n\t\t\t\t\t\t\tquoid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp,  div, vatcode, description, \n\t\t\t\t\t\t\taccount\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$quoid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t'{$accounts[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $quo['chrgvat'], $excluding, $quo['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $exvat = "y";
                } else {
                    $exvat = "n";
                }
                $wtd = $whids[$keys];
                # insert quote items
                $sql = "\n\t\t\t\t\t\tINSERT INTO quote_items (\n\t\t\t\t\t\t\tquoid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp, div, vatcode\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$quoid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "','{$vatcodes[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert quote items to Cubit.", SELF);
                # update stock(alloc + qty)
                # $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                # $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>";
            //&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $quo['chrgvat'], $excluding, $quo['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //			$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $delvat += 0;
    //manual error handling
    if (!isset($lead)) {
        $lead = "";
    }
    # insert quote to DB
    $sql = "\n\t\t\tUPDATE quotes \n\t\t\tSET delvat='{$delvat}',cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', \n\t\t\t\tsalespn = '{$salespn}', odate = '{$odate}', ncdate = '{$ncdate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', \n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', discount='{$traddiscmt}', \n\t\t\t\tdelivery='{$delexvat}', lead = '{$lead}' \n\t\t\tWHERE quoid = '{$quoid}'";
    $rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM quote_data WHERE quoid='{$quoid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\t\tINSERT INTO quote_data (\n\t\t\t\tquoid, dept, customer, addr1, div\n\t\t\t) VALUES (\n\t\t\t\t'{$quoid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "'\n\t\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert quote data to Cubit.", SELF);
    $ncdate = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
    /* --- Start button Listeners --- */
    if (isset($donePrnt)) {
        $sql = "UPDATE quotes SET done='y' WHERE quoid='{$quoid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update quote status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('pdf/pdf-quote.php?quoid={$quoid}');\n\t\t\t\tmove('quote-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($doneBtn)) {
        # insert quote to DB
        $sql = "UPDATE quotes SET done = 'y' WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update quote status in Cubit.", SELF);
        #add lead
        if (isset($lead) and $lead == "yes") {
            db_conn("crm");
            $sql = "\n\t\t\t\tINSERT INTO leads (\n\t\t\t\t\tsurname, date, by, con, div, supp_id, cust_id, lead_source, birthdate, reports_to_id, \n\t\t\t\t\tassigned_to, assigned_to_id, account_id, gender, website, salespid, ncdate, team_id, dept_id, tell, \n\t\t\t\t\thadd, ref\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cust['surname']}', 'now', '" . USER_NAME . "', 'No', '" . USER_DIV . "', '0', '0', '0', 'now', '0', \n\t\t\t\t\t'" . USER_NAME . "', '2', '0', 'Male', 'http://', '0', '{$ncdate}', '0', '0', '{$cust['cellno']}', \n\t\t\t\t\t'{$cust['addr1']}', ''\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
            $lead_id = pglib_lastid("leads", "id");
        }
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($doneBtn)) {
        //old <a target='_blank' href='quote-print.php?quoid=$quoid'>Print Quote</a>
        // Final Laytout
        // 		$write = "
        // 			<table ".TMPL_tblDflts.">
        // 				<tr>
        // 					<th colspan='2'>New Quote</th>
        // 				</tr>
        // 				<tr class='".bg_class()."'>
        // 					<td>Quote for customer <b>$cust[cusname] $cust[surname]</b> has been recorded.</td>
        // 					<td><input type='button' onClick=\"javascript:printer('pdf/quote-pdf-print.php?quoid=$quoid')\" value='Print Quote'></td>
        // 					<td><input type='button' onclick='javascript:move(\"quote-email.php?evs=$quoid\")' value='Email'></td>
        // 				</tr>
        // 			</table>"
        // 			.mkQuickLinks(
        // 				ql("quote-view.php", "View Quotes"),
        // 				ql("customers-new.php", "New Customer")
        // 			);
        // 		return $write;
        return "\n\t\t\t<script>\n\t\t\t\tprinter('quote-print.php?quoid={$quoid}');\n\t\t\t\tdocument.location='quote-new.php';\n\t\t\t</script>";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Quote Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Quote for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("quote-view.php", "View Quotes"), ql("customers-new.php", "New Customer"));
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
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;
}