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'];
    }
    /* make named r2s snapshop */
    r2sListSet("invoice_stk_view");
    # Set up table to display in
    $printInv = "\n\t\t<h3>View invoices. Date Range {$fromdate} to {$todate}</h3>\n\t\t<form action='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>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 colspan='2'>Balance</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='6'>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    if (isset($all)) {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    } else {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND cusnum = {$cusnum} AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    }
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    // Retrieve the reprint setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'> No Outstanding Invoices found for the selected customer.</li><br>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            # Format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['printed'] == "n") {
                $Dis = "TI {$inv['invid']}";
            } else {
                $Dis = "{$inv['invnum']}";
            }
            $det = "invoice-details.php";
            $print = "invoice-print.php";
            $edit = "cust-credit-stockinv.php";
            $reprint = "invoice-reprint.php";
            if (isset($mode) && $mode == "creditnote") {
                $note = "<input type='button' onClick='document.location.href=\"invoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
            } else {
                $note = "<a href='invoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
            }
            if ($template == "default") {
                $template = "invoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $pdfreprint = $template;
            $chbox = "<input type=checkbox name='invids[]' value='{$inv['invid']}' checked=yes>";
            if ($inv['location'] == 'int') {
                $det = "intinvoice-details.php";
                $print = "intinvoice-print.php";
                $edit = "intinvoice-new.php";
                $reprint = "intinvoice-reprint.php";
                if (isset($mode) && $mode == "creditnote") {
                    $note = "<input type='button' onClick='document.location.href=\"intinvoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
                } else {
                    $note = "<a href='intinvoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
                }
                if ($template == "default") {
                    $template = "intinvoice-pdf-reprint.php";
                } elseif ($template == "new") {
                    $template = "pdf-tax-invoice.php";
                }
                $pdfreprint = $template;
                $chbox = "<br>";
            }
            if ($inv['serd'] == 'n') {
                $chbox = "";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $fbal = "{$sp4}--{$sp4}";
            $bcurr = CUR;
            if ($inv['location'] == 'int') {
                $fbal = "{$sp4} {$inv['currency']} {$inv['fbalance']}";
                $bcurr = $inv['currency'];
            }
            //<a href='invoice-email.php?invid=$inv[invid]'>Email</a>
            $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>{$Dis}</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 align='right' nowrap>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td align='right' nowrap> {$fbal}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?invid={$inv['invid']}'>Details</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$inv['invid']}]'></td>";
            if ($inv['printed'] == "n") {
                $printInv .= "\n\t\t\t\t\t\t<td><a href='{$edit}?invid={$inv['invid']}&cont=1&letters='>Edit</a></td>\n\t\t\t\t\t\t<td><a target='_blank' href='{$print}?invid={$inv['invid']}'>Process</a></td>\n\t\t\t\t\t\t<td align='center'>{$chbox}</td>\n\t\t\t\t\t\t<td>&nbsp</td>\n\t\t\t\t\t</tr>";
            } else {
                db_conn($inv["prd"]);
                $sql = "SELECT * FROM inv_notes WHERE invid='{$inv['invid']}'";
                $note_rslt = db_exec($sql) or errDie("Unable to retrieve credit notes from Cubit.");
                if (!pg_num_rows($note_rslt)) {
                    $delnote = "<td><a target='_blank' href='invoice-delnote.php?invid={$inv['invid']}'>Delivery Note</a></td>";
                } else {
                    $delnote = "<td>&nbsp;</td>";
                }
                if (round($inv['total'], 0) != round($inv['nbal'], 0)) {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>{$note}</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                } else {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>Settled</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                }
            }
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    $tot2 = sprint($tot2);
    //	$bgColor = bgcolor($i);
    // Layout
    if ($i > 0) {
        $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='6'>Totals:{$i}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot1}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot2}</td>\n\t\t\t\t\t<td colspan='3'><br></td>\n\t\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Email Selected' name='email'>\n\t\t\t\t\t</td><td colspan='10' align='right'><input type='submit' value='Process Selected' name='proc'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $printInv .= "\n\t\t</table>\n\t\t</form>";
    return $printInv;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    if (!isset($button) && isset($starting)) {
        return slct();
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid Non-Stock Invoice number.");
    } elseif (isset($ctyp)) {
        $val = $ctyp . "val";
        if (isset(${$val})) {
            $tval = ${$val};
            $v->isOk($tval, "num", 1, 20, "Invalid Selection.");
        }
    }
    if (isset($cusnum) && customer_overdue($cusnum)) {
        $v->addError(0, "Customer is overdue, account blocked!");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slct($error);
        $confirm = "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($invid) && isset($ctyp)) {
        $val = $ctyp . "val";
        if (!isset(${$val})) {
            ${$val} = "";
        }
        $tval = ${$val};
        if (isset($bankid)) {
            $bankid += 0;
            $acc = $bankid;
        } else {
            $acc = 0;
        }
        $invid = create_dummy(0, $ctyp, $tval, $acc);
    }
    # 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);
    # check if invoice has been printed
    if ($inv['done'] == "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;
    }
    /* --- Start Drop Downs --- */
    # format date
    list($ninv_year, $ninv_month, $ninv_day) = explode("-", $inv['odate']);
    # keep the charge vat option stable
    if ($inv['chrgvat'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnone = "";
    } elseif ($inv['chrgvat'] == "no") {
        $chy = "";
        $chn = "checked=yes";
        $chnone = "";
    } else {
        $chy = "";
        $chn = "";
        $chnone = "checked=yes";
    }
    # Days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>VAT Code</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $stkd['amt'] = round($stkd['amt'], 2);
        $chk = "";
        if ($stkd['vatex'] == 'y') {
            $chk = "checked=yes";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl);
        $vats = "<select name='vatcodes[]'>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatex'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $vats .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $vats .= "</option>";
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center' nowrap><input type='hidden' name='des[{$i}]' value='{$stkd['description']}'>" . nl2br($stkd['description']) . "</td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[{$i}]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[{$i}]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td><input type='hidden' name='amt[{$i}]' value='" . sprint($stkd["amt"]) . "'> " . CUR . " " . sprint($stkd["amt"]) . "</td>\n\t\t\t\t<!--<td align='center'><input type='checkbox' name='vatex[{$i}]' value='{$i}' {$chk}></td>-->\n\t\t\t\t<td align='center'>{$vats}</td>\n\t\t\t\t<td align='center'><input type='checkbox' name='remprod[{$i}]' value='{$i}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t</tr>";
        $i++;
    }
    # Look above(remprod keys)
    $keyy = $i;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    if (!isset($error) and strlen($error) == 0) {
        $bodydata = "";
    }
    //document.editForm.bodydata.value = editArea.document.body.innerHTML;
    //	if (isset ($bodydata) AND strlen ($bodydata) > 0){
    //print "$bodydata";
    //		$doset = "
    //			<script>
    //				editArea.document.body.innerHTML = '".strip_tags($bodydata)."';
    //			</script>";
    //	}else {
    //		$doset = "";
    //	}
    //old
    //					<td align='center'><input type='text' size='50' name='des[]' value=''></td>
    if ($i == 0 || isset($diffwhBtn)) {
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'>\n\t\t\t\t\t<table id='tblCtrls' width='420px' height='30px' border='0' cellspacing='0' cellpadding='0' bgcolor='#D6D3CE'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='tdClass'>\n\t\t\t\t\t\t\t\t<img alt='Bold' class='buttonClass' src='images/bold.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doBold()'>\n\t\t\t\t\t\t\t\t<img alt='Italic' class='buttonClass' src='images/italic.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doItalic()'>\n\t\t\t\t\t\t\t\t<img alt='Underline' class='buttonClass' src='images/underline.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doUnderline()'>\n\t\t\t\t\t\t\t\t<img alt='Left' class='buttonClass' src='images/left.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doLeft()'>\n\t\t\t\t\t\t\t\t<img alt='Center' class='buttonClass' src='images/center.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doCenter()'>\n\t\t\t\t\t\t\t\t<img alt='Right' class='buttonClass' src='images/right.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doRight()'>\n\t\t\t\t\t\t\t\t<img alt='Ordered List' class='buttonClass' src='images/ordlist.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doOrdList()'>\n\t\t\t\t\t\t\t\t<img alt='Bulleted List' class='buttonClass' src='images/bullist.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doBulList()'>\n\t\t\t\t\t\t\t\t<img alt='Horizontal Rule' class='buttonClass' src='images/rule.gif' onMouseOver='controlSelOn(this)' onMouseOut='controlSelOff(this)' onMouseDown='controlSelDown(this)' onMouseUp='controlSelUp(this)' onClick='doRule()'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td class='tdClass' align=right>\n\t\t\t\t\t\t\t\t<select name='selSize' onChange='doSize(this.options[this.selectedIndex].value)'>\n\t\t\t\t\t\t\t\t\t<option value=''>-- Font Size --</option>\n\t\t\t\t\t\t\t\t\t<option value='1'>Very Small</option>\n\t\t\t\t\t\t\t\t\t<option value='2'>Small</option>\n\t\t\t\t\t\t\t\t\t<option value='3'>Medium</option>\n\t\t\t\t\t\t\t\t\t<option value='4'>Large</option>\n\t\t\t\t\t\t\t\t\t<option value='5'>Larger</option>\n\t\t\t\t\t\t\t\t\t<option value='6'>Very Large</option>\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<iframe name='editArea' id='editArea' style='width: 420px; height:160px; background: #FFFFFF;'></iframe>\n\t\t\t\t\t<input type='hidden' name='bodydata' value=''>\n\t\t\t\t\t<input type='hidden' name='counter' value='{$i}'>\n\t\t\t\t</td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[{$i}]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[{$i}]'></td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $inv['subtot'];
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    db_conn('cubit');
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['tval']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cust = pg_fetch_array($custRslt);
        if (!empty($cust["cusname"])) {
            $cn = "{$cust['cusname']} {$cust['surname']}";
        } else {
            $cn = "{$cust['surname']}";
        }
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='cusnum' value='{$cust['cusnum']}' />\n\t\t\t<input type='hidden' name='cusname' value='{$cn}'>\n\t\t\t<input type='hidden' name='cusaddr' value='{$cust['addr1']}'>\n\t\t\t<input type='hidden' name='cusvatno' value='{$cust['vatnum']}'>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'>{$cust['cusname']} {$cust['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer Address</td>\n\t\t\t\t<td valign='center'><pre>{$cust['addr1']}</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t<td valign='center'>{$cust['vatnum']}</td>\n\t\t\t</tr>";
    } elseif ($inv['ctyp'] == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['tval']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='middle'><input type='text' name='cusname' value='{$inv['cusname']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t<td valign='middle'><textarea name='cusaddr' cols='18' rows='3'>{$inv['cusaddr']}</textarea></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer VAT No.</td>\n\t\t\t\t<td valign='middle'><input type='text' name='cusvatno' value='{$inv['cusvatno']}'></td>\n\t\t\t</tr>";
    } else {
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='middle'><input type='text' name='cusname' value='{$inv['cusname']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t<td valign='middle'><textarea name='cusaddr' cols='18' rows='3'>{$inv['cusaddr']}</textarea></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer VAT No.</td>\n\t\t\t\t<td valign='middle'><input type='text' name='cusvatno' value='{$inv['cusvatno']}'></td>\n\t\t\t</tr>";
    }
    # Get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        if (isset($cust) and is_array($cust) and strlen($inv['salespn']) < 1) {
            #if salespn == NULL search for customer default ...
            $get_salesp = "SELECT salesp FROM salespeople WHERE salespid = '{$cust['sales_rep']}' LIMIT 1";
            $run_salesp = db_exec($get_salesp) or errDie("Unable to get sales perosn information.");
            $inv['salespn'] = pg_fetch_result($run_salesp, 0, 0);
        }
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "\n\t\t<td>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t\t<td>Print</td>\n\t\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</td>";
    // Retrieve the default comments
    db_conn("cubit");
    $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
    $cmntRslt = db_exec($sql) or errDie("Unable to retrieve default comment from Cubit.");
    if (empty($inv["remarks"])) {
        $remarks = base64_decode(pg_fetch_result($cmntRslt, 0));
    } else {
        $remarks = $inv["remarks"];
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $deldate = explode("-", $inv["deldate"]);
    $showdoc_html = "'" . str_replace("<div style=\"text-align: left;\"><br></div>", "", $bodydata) . "'";
    if (isset($diffwhBtn) or isset($upBtn) or isset($doneBtn) or isset($print)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t<script language='JavaScript'>\n\t\t\tfunction update() {\n\t\t\t\tdocument.editForm.bodydata.value = editArea.document.body.innerHTML;\n\t\t\t\tdocument.editForm.submit();\n\t\t\t}\n\t\t\tfunction Init() {\n\t\t\t\teditArea.document.designMode = 'On';\n\t\t\t\teditArea.document.body.innerHTML = {$showdoc_html};\n\t\t\t\teditArea.document.execCommand('justifyleft', false, null);\n\t\t\t}\n\t\t\tfunction controlSelOn(ctrl) {\n\t\t\t\tctrl.style.borderColor = '#000000';\n\t\t\t\tctrl.style.backgroundColor = '#B5BED6';\n\t\t\t\tctrl.style.cursor = 'hand';\n\t\t\t}\n\t\t\tfunction controlSelOff(ctrl) {\n\t\t\t\tctrl.style.borderColor = '#D6D3CE';\n\t\t\t\tctrl.style.backgroundColor = '#D6D3CE';\n\t\t\t}\n\t\t\tfunction controlSelDown(ctrl) {\n\t\t\t\tctrl.style.backgroundColor = '#8492B5';\n\t\t\t}\n\t\t\tfunction controlSelUp(ctrl) {\n\t\t\t\tctrl.style.backgroundColor = '#B5BED6';\n\t\t\t}\n\t\t\tfunction doBold() {\n\t\t\t\teditArea.document.execCommand('bold', false, null);\n\t\t\t}\n\t\t\tfunction doItalic() {\n\t\t\t\teditArea.document.execCommand('italic', false, null);\n\t\t\t}\n\t\t\tfunction doUnderline() {\n\t\t\t\teditArea.document.execCommand('underline', false, null);\n\t\t\t}\n\t\t\tfunction doLeft() {\n\t\t\t\teditArea.document.execCommand('justifyleft', false, null);\n\t\t\t}\n\t\t\tfunction doCenter() {\n\t\t\t\teditArea.document.execCommand('justifycenter', false, null);\n\t\t\t}\n\t\t\tfunction doRight() {\n\t\t\t\teditArea.document.execCommand('justifyright', false, null);\n\t\t\t}\n\t\t\tfunction doOrdList() {\n\t\t\t\teditArea.document.execCommand('insertorderedlist', false, null);\n\t\t\t}\n\t\t\tfunction doBulList() {\n\t\t\t\teditArea.document.execCommand('insertunorderedlist', false, null);\n\t\t\t}\n\t\t\tfunction doRule() {\n\t\t\t\teditArea.document.execCommand('inserthorizontalrule', false, null);\n\t\t\t}\n\t\t\tfunction doSize(fSize) {\n\t\t\t\tif(fSize != '')\n\t\t\t\t\teditArea.document.execCommand('fontsize', false, fSize);\n\t\t\t}\n\t\t\twindow.onload = Init;\n\t\t</script>\n\t\t<center>\n\t\t<h3>New Multi Line Invoice</h3>\n\t\t<form action='" . SELF . "' method='POST' name='editForm' enctype='multipart/form-data'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>Non-Stock Invoice Details</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Non-Stock Invoice No.</td>\n\t\t\t\t\t\t\t<td valign='center'>TI {$inv['invid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Proforma Invoice No.</td>\n\t\t\t\t\t\t\t<td><input type='text' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("ninv", $ninv_year, $ninv_month, $ninv_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='yes' {$chy}> No<input type=radio size=7 name=chrgvat value='no' {$chn}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t{$sales}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$remarks}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align=right>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['vat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' name='diffwhBtn' onClick='update();' value='Add Item'> |</td>\n\t\t\t\t<td><input type='submit' name='upBtn' onClick='update();' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
if (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "view":
            require_lib("docman");
            $OUTPUT = printPurch($_POST);
            break;
        case "export":
            $OUTPUT = export($_POST);
            break;
        default:
            $OUTPUT = slct();
            break;
    }
} else {
    # Display default output
    $OUTPUT = slct();
}
require "template.php";
# Default view
function slct()
{
    db_conn(YR_DB);
    $sql = "SELECT * FROM info WHERE prdname !=''";
    $prdRslt = db_exec($sql);
    if (pg_numrows($prdRslt) < 1) {
        return "<li class='err'>ERROR : There are no periods set for the current year.</li>";
    }
    $Prds = "<select name='prd'>";
    while ($prd = pg_fetch_array($prdRslt)) {
        if ($prd['prddb'] == PRD_DB) {
            $sel = "selected";
function printStk($_POST, $errs = "")
{
    extract($_POST);
    $fields = array();
    $fields["search_val"] = "[_BLANK_]";
    extract($fields, EXTR_SKIP);
    if (!isset($whid) or count($whid) < 1) {
        return slct();
    }
    if (!is_array($whid)) {
        $temp = $whid;
        $whid = array();
        $whid[] = $temp;
    }
    if (!isset($sortby)) {
        $sortby = "normal";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($catid, "num", 1, 50, "Invalid Category.");
    $v->isOk($clasid, "num", 1, 50, "Invalid Classification.");
    $v->isOk($sortby, "string", 1, 10, "Invalid Sort Selection.");
    foreach ($whid as $temp) {
        $v->isOk($temp, "num", 1, 50, "Invalid Warehouse.");
    }
    $Whe = "";
    if ($catid != 0) {
        $Whe .= " AND catid = '{$catid}'";
    }
    if ($clasid != 0) {
        $Whe .= " AND prdcls = '{$clasid}'";
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li><br>";
        }
        return $confirm;
    }
    if (!isset($sortby)) {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "";
    } elseif ($sortby == "cat") {
        $sel1 = "";
        $sel2 = "checked='yes'";
        $sel3 = "";
    } elseif ($sortby == "class") {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "checked='yes'";
    } else {
        $sel1 = "checked='yes'";
        $sel2 = "";
        $sel3 = "";
    }
    $whids = "";
    foreach ($whid as $temp) {
        $whids .= "<input type='hidden' name='whid[]' value='{$temp}'>";
    }
    if ($key == "export") {
        $pure = true;
    } else {
        $pure = false;
    }
    $Whe .= " AND ((lower(stkcod) LIKE lower('%{$search_val}%')) OR (lower(stkdes) LIKE lower('%{$search_val}%')))";
    if ($search_val == "[_BLANK_]") {
        $search_val = "";
    }
    # Set up table to display in
    if ($pure) {
        $OUT = "<table " . TMPL_tblDflts . ">";
    } else {
        $OUT = "\n\t\t<h3>View Stock</h3>\n\t\t{$errs}\n\t\t<table " . TMPL_tblDflts . " width='30%'>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t<input type='hidden' name='search_val' value='{$search_val}'>\n\t\t\t{$whids}\n\t\t\t<tr>\n\t\t\t\t<th>Sort By:</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='sortby' {$sel1} value='normal' onChange='javascript:document.form1.submit();'> Normal\n\t\t\t\t\t<input type='radio' name='sortby' {$sel2} value='cat' onChange='javascript:document.form1.submit();'> Category\n\t\t\t\t\t<input type='radio' name='sortby' {$sel3} value='class' onChange='javascript:document.form1.submit();'> Classification\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Search</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='text' size='25' name='search_val' value='{$search_val}'> \n\t\t\t\t\t<input type='submit' value='Search'>\n\t\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</form>\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST' name='form2'>\n\t\t\t<input type='hidden' name='key' value='remove'>";
    }
    #search parms
    if ($sortby == "cat") {
        $Ord = "catname,stkcod";
    } elseif ($sortby == "class") {
        $Ord = "classname,stkcod";
    } else {
        $Ord = "stkcod";
    }
    $stores = array();
    if ($whid != "0") {
        foreach ($whid as $temp) {
            if ($temp != 0) {
                $stores[] = " whid = '{$temp}'";
            }
        }
        if (count($stores) > 0) {
            $stores = implode(" OR ", $stores);
        } else {
            $stores = "true";
        }
    } else {
        $stores = "true";
    }
    # connect to database
    db_connect();
    if (!isset($offset)) {
        $offset = 0;
    }
    if (isset($next)) {
        $offset = $offset + 100;
    }
    if (isset($prev)) {
        $offset = $offset - 100;
    }
    if ($offset < 0) {
        $offset = 0;
    }
    if ($offset != 0) {
        $prev_but = "<input type='submit' name='prev' value='Previous'>";
    } else {
        $prev_but = "";
    }
    # Query server
    $i = 0;
    $searchs = "SELECT * FROM stock WHERE units<=0 AND ({$stores}) AND div = '" . USER_DIV . "' {$Whe} ORDER BY {$Ord} ASC LIMIT 100 OFFSET {$offset}";
    $stkRslt = db_exec($searchs) or errDie("Unable to retrieve stocks from database.");
    if (pg_numrows($stkRslt) < 1) {
        $whids = "<tr><li class='err'> No Stock Items Found. Please enter the first few letters of the stock item</li></td></tr>";
        //		return "
        //			<li class='err'> There are no stock items.</li>
        //			<p>
        //			<table ".TMPL_tblDflts." width='15%'>
        //				".TBL_BR."
        //				<tr><th>Quick Links</th></tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='stock-view.php'>Back</a></td>
        //				</tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='stock-add.php'>Add Stock</a></td>
        //				</tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='main.php'>Main Menu</a></td>
        //				</tr>
        //			</table>";
    }
    if (pg_numrows($stkRslt) > 0 and pg_numrows($stkRslt) == 100) {
        $next_but = "<input type='submit' name='next' value='Next'>";
    } else {
        $next_but = "";
    }
    $heading = "";
    $showheading = "";
    while ($stk = pg_fetch_array($stkRslt)) {
        $serd = $stk['serd'] == 'yes' ? $stk['units'] > 0 ? "<a href='stock-serials.php?stkid={$stk['stkid']}'>Allocate Serial No.</a>" : "<br>" : "<br>";
        $stk['selamt'] = sprint($stk['selamt']);
        if ($sortby == "cat") {
            if ($stk['catname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['catname']}</b></font></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        } elseif ($sortby == "class") {
            if ($stk['classname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['classname']}</b></font></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        } else {
            if ($heading == "normal") {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        }
        // Retrieve store name from the database
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid='{$stk['whid']}'";
        $wh_rslt = db_exec($sql) or errDie("Unable to retrieve warehouses from Cubit.");
        $whname = pg_fetch_result($wh_rslt, 0);
        $OUT .= $showheading;
        $OUT .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$whname}</td>\n\t\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t<td>{$stk['classname']}</td>\n\t\t\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['units']}</td>\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stk['selamt']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['alloc']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['ordered']}</td>";
        if (!$pure) {
            // Check if we've got a recipe
            $sql = "SELECT * FROM cubit.recipies WHERE m_stock_id='{$stk['stkid']}'";
            $recipe_rslt = db_exec($sql) or errDie("Unable to retrieve recipe.");
            // Create a link if neccessary
            if (pg_num_rows($recipe_rslt)) {
                $manu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=manuout'>\n\t\t\t\t\t\tManufacture\n\t\t\t\t\t</a>";
                $unmanu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=unmanuout'>\n\t\t\t\t\t\tDisassemble\n\t\t\t\t\t</a>";
            } else {
                $manu_href = "";
                $unmanu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=unmanuout'>\n\t\t\t\t\t\tDisassemble\n\t\t\t\t\t</a>";
            }
            $OUT .= "\n\t\t\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>Report</a></td>\n\t\t\t\t\t\t<td><a href='stock-det.php?stkid={$stk['stkid']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='stock-edit.php?stkid={$stk['stkid']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='stock-balance.php?stkid={$stk['stkid']}'>Transaction</a></td>\n\t\t\t\t\t\t<td>{$serd}</td>\n\t\t\t\t\t\t<td><a href='pos.php?id={$stk['stkid']}'>Barcode</a></td>\n\t\t\t\t\t\t<td>{$manu_href}</td>\n\t\t\t\t\t\t<td>{$unmanu_href}</td>";
            if ($stk['blocked'] == 'y') {
                $OUT .= "<td><a href='stock-unblock.php?stkid={$stk['stkid']}'>Unblock</a></td>";
            } else {
                $OUT .= "<td><a href='stock-block.php?stkid={$stk['stkid']}'>Block</a></td>";
            }
            if ($stk['units'] < 1 && $stk['alloc'] < 1 && $stk['lcsprice'] == 0 && $stk['csprice'] == 0) {
                $OUT .= "\n\t\t\t\t\t\t\t\t<td><a href='stock-rem.php?stkid={$stk['stkid']}'>Remove</a></td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remids[]' value='{$stk['stkid']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t";
            } elseif ($stk['alloc'] > 0) {
                $OUT .= "\n\t\t\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-alloc.php?stkid={$stk['stkid']}\")'>View Allocation</a></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            } else {
                $OUT .= "\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            }
        }
        if ($sortby == "cat") {
            $heading = $stk['catname'];
        } elseif ($sortby == "class") {
            $heading = $stk['classname'];
        } else {
            $heading = "normal";
        }
    }
    r2sListSet("stock_view");
    if (!$pure) {
        $OUT .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='20' align='right'><input type='submit' value='Remove Selected'></td>\n\t\t\t\t</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{$whids}\n\t\t\t\t<input type='hidden' name='offset' value='{$offset}'>\n\t\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t\t<input type='hidden' name='sortby' value='{$sortby}'>\n\t\t\t\t<input type='hidden' name='search_val' value='{$search_val}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$prev_but}</td>\n\t\t\t\t\t<td colspan='3'></td>\n\t\t\t\t\t<td>{$next_but}</td>\n\t\t\t\t</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='export'>\n\t\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t\t<input type='hidden' name='sortby' value='{$sortby}'>\n\t\t\t\t{$whids}\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr><td><input type='submit' value='Export to Spreadsheet'>\n\t\t\t</form>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t\t<tr><td><br></td></tr>\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='stock-add.php'>Add Stock</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>";
    } else {
        $OUT .= "\n\t\t\t\t\t</form>\n\t\t\t\t\t</table>\n\t\t\t\t";
    }
    return $OUT;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($purid)) {
        $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Order number.");
    } else {
        $v->isOk($supid, "num", 1, 20, "Invalid Supplier number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm = $error . slct();
        return $confirm;
    }
    if (!isset($purid)) {
        $purid = create_dummy(0, $supid);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li class='err'>purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if ($pur['xrate'] == 0) {
        $pur['xrate'] = 1;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to view Supplier");
    if (pg_numrows($supRslt) < 1) {
        db_connect();
        # Query server for supplier info
        $sql = "SELECT * FROM suppliers WHERE location = 'int' AND div = '" . USER_DIV . "' ORDER BY supname ASC";
        $supRslt = db_exec($sql) or errDie("Unable to view suppliers");
        if (pg_numrows($supRslt) < 1) {
            $err = "<li class='err'>No Supplier found in database.</li>";
            return view_err($_POST, $err);
        } else {
            $suppliers = "<select name='supid' onChange='javascript:document.form.submit();'>";
            $suppliers .= "<option value='-S' selected>Select Supplier</option>";
            while ($sup = pg_fetch_array($supRslt)) {
                $suppliers .= "<option value='{$sup['supid']}'>{$sup['supname']}</option>";
            }
            $suppliers .= "</select>";
        }
        # take care of the uset vars
        $supaddr = "";
        $accno = "";
        $fcid = $pur['fcid'];
    } else {
        db_connect();
        # Query server for supplier info
        $sql = "SELECT * FROM suppliers WHERE location = 'int' AND div = '" . USER_DIV . "' ORDER BY supname ASC";
        $supRslt = db_exec($sql) or errDie("Unable to view suppliers");
        if (pg_numrows($supRslt) < 1) {
            $err = "<li class='err'>No Supplier found in database.</li>";
            return view_err($_POST, $err);
        } else {
            $supid = $pur['supid'];
            $suppliers = "<select name='supid' onChange='javascript:document.form.submit();'>";
            $sel = "";
            $fcid = $pur['fcid'];
            while ($sup = pg_fetch_array($supRslt)) {
                if ($sup['supid'] == $supid) {
                    $sel = "selected";
                    $supaddr = "{$sup['supaddr']}";
                    $accno = $sup['supno'];
                    $fcid = $sup['fcid'];
                    $listid = $sup['listid'];
                } else {
                    $sel = "";
                    $supaddr = "";
                    $accno = "";
                }
                $suppliers .= "<option value='{$sup['supid']}' {$sel}>{$sup['supname']}</option>";
            }
            $suppliers .= "</select>";
        }
    }
    $currs = getSymbol($fcid);
    $curr = $currs['symbol'];
    $currsel = "{$currs['symbol']} - {$currs['descrip']}";
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($npuri_year, $npuri_month, $npuri_day) = explode("-", $pur['pdate']);
    list($del_year, $del_month, $del_day) = explode("-", $pur['ddate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th colspan='2'>UNIT PRICE</th>\n\t\t\t\t<th colspan='2'>DUTY</th>\n\t\t\t\t<th>LINE TOTAL</th>\n\t\t\t\t<th>COST PER UNIT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT * FROM nons_purint_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        /* -- Calculations -- */
        # Calculate cost amount bought
        $totamt = $stkd['qty'] * $stkd['cunitcost'];
        # Calculate percentage from subtotal
        if ($pur['subtot'] != 0) {
            $perc = ($totamt + $stkd['duty']) / $pur['subtot'] * 100;
        } else {
            $perc = 0;
        }
        # Get percentage from shipping charges
        $shipchrg = sprint($perc / 100 * $pur['shipchrg']);
        # Add shipping charges to amt
        $totamt = sprint($totamt + $shipchrg + $stkd['duty']);
        $unitamt = sprint($totamt / $stkd['qty']);
        /* -- End Calculations --*/
        $stkd['amt'] = sprint($stkd['amt']);
        $tip = "&nbsp;&nbsp;&nbsp;";
        if (isset($vatc[$key])) {
            $tip = "<font color='red'>#</font>";
            $error = "<div class='err'> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; Vat amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
        }
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value='{$stkd['cod']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value='{$stkd['des']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='cunitcost[]' value='{$stkd['cunitcost']}'> or </td>\n\t\t\t\t<td>" . CUR . " <input type='text' size='6' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='duty[]' value='{$stkd['duty']}'> or </td>\n\t\t\t\t<td><input type='text' size='3' name='dutyp[]' value='{$stkd['dutyp']}'>%</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> {$pur['curr']} {$stkd['amt']}</td>\n\t\t\t\t<td align='right'>{$pur['curr']} {$unitamt}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='checkbox' name='remprod[]' value='{$key}'>\n\t\t\t\t\t<input type='hidden' name='SCROLL' value='yes'>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
        list($year, $mon, $day) = explode("-", date("Y-m-d"));
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='cunitcost[]'> or </td>\n\t\t\t\t<td>" . CUR . " <input type='text' size='6' name='unitcost[]'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='duty[]'> or </td>\n\t\t\t\t<td><input type='text' size='3' name='dutyp[]'>%</td>\n\t\t\t\t<td>{$pur['curr']} 0.00</td>\n\t\t\t\t<td align='right'>{$pur['curr']} 0.00</td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        list($year, $mon, $day) = explode("-", date("Y-m-d"));
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='cunitcost[]'> or </td>\n\t\t\t\t<td>" . CUR . " <input type='text' size='6' name='unitcost[]'></td>\n\t\t\t\t<td>{$pur['curr']} <input type='text' size='6' name='duty[]'> or </td>\n\t\t\t\t<td><input type='text' size='3' name='dutyp[]'>%</td>\n\t\t\t\t<td>{$pur['curr']} 0.00</td>\n\t\t\t\t<td align='right'>{$pur['curr']} 0.00</td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
        $key++;
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    $pur['tax'] = sprint($pur['tax']);
    $pur['shipchrg'] = sprint($pur['shipchrg']);
    $pur['cusid'] += 0;
    if ($pur['cusid'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $pur['cusid'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $pur['cusid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    /* --- End Some calculations --- */
    if (isset($diffwhBtn) or isset($upBtn) or isset($doneBtn) or isset($recv) or isset($donePrnt)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details = "\n\t\t<center>\n\t\t<h3>New International Non-Stock Order</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t<td valign='center'>{$suppliers}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t<td valign='center'>{$accno}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($supaddr) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Order Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Non-Stock Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$ordernum}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center' nowrap='t'>" . mkDateSelect("npuri", $npuri_year, $npuri_month, $npuri_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Foreign Currency</td>\n\t\t\t\t\t\t\t<td valign='center'>{$currsel} &nbsp;&nbsp;Exchange rate " . CUR . " <input type='text' size='7' name='xrate' value='{$pur['xrate']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Tax</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} <input type='text' size='7' name='tax' value='{$pur['tax']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Shipping Charges</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} <input type='text' size='7' name='shipchrg' value='{$pur['fshipchrg']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("del", $del_year, $del_month, $del_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purch-int-view.php'>View International Non-Stock Orders</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align=right>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>{$pur['curr']} <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Shipping Charges</td>\n\t\t\t\t\t\t\t<td align='right'>{$pur['curr']} {$pur['shipchrg']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Tax </td>\n\t\t\t\t\t\t\t<td align='right'>{$pur['curr']} {$pur['tax']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>{$pur['curr']} <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name='diffwhBtn' type='submit' value='Add Item'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Order number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($supid, "num", 1, 20, "Invalid supplier account number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class=err>" . $e["msg"];
        }
        return slct($_POST, $error);
        $confirm = "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li class=err>purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class=err> Error : Order number <b>{$purid}</b> has already been received.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    $supacc = "<select name='supacc'>";
    core_connect();
    $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY accname ASC";
    $accRslt = db_exec($sql);
    if (pg_numrows($accRslt) < 1) {
        return "<li>There are No accounts in Cubit.";
    }
    while ($acc = pg_fetch_array($accRslt)) {
        # Check Disable
        if (isDisabled($acc['accid'])) {
            continue;
        }
        $supacc .= "<option value='{$acc['accid']}'>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</option>";
    }
    $supacc .= "</select>";
    # Get selected supplier info
    db_connect();
    $hide = "";
    if (isset($ctyp) && $ctyp == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class=err> Supplier not Found.";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            $supacc = $sup['supno'];
            $hide = "<input type=hidden name=supid value='{$supid}'><input type=hidden name=ctyp value='{$ctyp}'>";
        }
    } elseif (isset($ctyp) && $ctyp == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class=err> Department not Found.";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = "{$dept['deptname']} - Cash on Hand";
            $hide = "<input type=hidden name=deptid value='{$deptid}'><input type=hidden name=ctyp value='{$ctyp}'>";
        }
    } elseif (isset($ctyp) && $ctyp == 'p') {
        core_connect();
        # Get Petty cash account
        $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
        # Get account name for thy lame User's Sake
        $accRslt = get("core", "*", "accounts", "accid", $cashacc);
        if (pg_numrows($accRslt) < 1) {
            return "<li class=err> Petty Cash Account not found.";
        }
        $acc = pg_fetch_array($accRslt);
        $supacc = "{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}";
        $hide = "<input type=hidden name=supacc value='{$cashacc}'><input type=hidden name=ctyp value='{$ctyp}'>";
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=100%>\n\t<tr><th>ITEM NUMBER</th><th>DESCRIPTION</th><th>QTY RECEIVED</th><th>UNIT PRICE</th><th>DELIVERY DATE</th><th>AMOUNT</th><tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT *, (qty - rqty) as qty FROM nons_pur_items  WHERE purid = '{$purid}' AND (qty - rqty) > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        # put in product
        $products .= "<tr class='bg-odd'><td><input type=hidden size=4 name=cod[] value='{$stkd['cod']}'>{$stkd['cod']}</td><td>{$stkd['des']}</td><td><input type=hidden name=qts[] value='{$stkd['qty']}'><input type=text size=5 name=qtys[] value='{$stkd['qty']}'></td><td><input type=hidden size=4 name=unitcost[] value='{$stkd['unitcost']}'>{$stkd['unitcost']}</td><td>{$sday}-{$smon}-{$syear}</td><td>" . CUR . " {$stkd['amt']}</td></tr>";
        $key++;
    }
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    db_conn('cubit');
    $Sql = "SELECT * FROM assets WHERE (id = '{$pur['assid']}' AND div = '" . USER_DIV . "')";
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    if (pg_numrows($Rslt) < 1) {
        return "<li class=err> - Asset not Found";
    }
    $asset = pg_fetch_array($Rslt);
    /* -- Final Layout -- */
    $details = "<center><h3>Non-Stock Asset Order received</h3>\n\t<form action='" . SELF . "' method=post name=form>\n\t<input type=hidden name=key value=update>\n\t<input type=hidden name=purid value='{$purid}'>\n\t{$hide}\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=95%>\n\t<tr><td valign=top>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\n\t\t\t<tr><th colspan=2> Supplier Details </th></tr>\n\t\t\t<tr class='bg-odd'><td>Supplier</td><td valign=center>{$pur['supplier']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Supplier Address</td><td valign=center><pre>{$pur['supaddr']}</pre></td></tr>\n\t\t\t<tr class='bg-odd' " . ass("Select the account you wish to Credit") . "><td>Account</td><td>{$supacc}</td></tr>\n\t\t</table>\n\t</td><td valign=top align=right>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\n\t\t\t<tr><th colspan=2> Non-Stock Order Details </th></tr>\n\t\t\t<tr class='bg-even'><td>Asset</td><td valign=center>{$asset['des']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Non-Stock Order No.</td><td valign=center>{$pur['purnum']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Ref No.</td><td valign=center><input type=text name=refno size=10 value='{$pur['refno']}'></td></tr>\n\t\t\t<tr class='bg-odd'><td>Terms</td><td valign=center>{$pur['terms']} Days</td></tr>\n\t\t\t<tr class='bg-even'><td>Date</td><td valign=center><input type=text size=2 name=pday maxlength=2 value='{$pday}'>-<input type=text size=2 name=pmon maxlength=2 value='{$pmon}'>-<input type=text size=4 name=pyear maxlength=4 value='{$pyear}'> DD-MM-YYYY</td></tr>\n\t\t\t<tr class='bg-odd'><td>VAT Inclusive</td><td valign=center>{$pur['vatinc']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Charges</td><td valign=center>" . CUR . " <input type=text name=shipchrg size=10 value='{$pur['shipchrg']}'></td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td colspan=2>{$products}</td></tr>\n\t<tr><td>\n\t\t<p>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th width=25%>Quick Links</th><th width=25%>Remarks</th><td rowspan=5 valign=top width=50%>{$error}</td></tr>\n\t\t\t<tr><td class='bg-odd'><a href='nons-purchase-new.php'>New Order</a></td><td class='bg-odd' rowspan=4 align=center valign=top><textarea name=remarks rows=4 cols=20>{$pur['remarks']}</textarea></td></tr>\n\t\t\t<tr class='bg-odd'><td><a href='nons-purchase-view.php'>View Orders</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\n\t\t</table>\n\t</td><td align=right>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=80%>\n\t\t\t<tr class='bg-odd'><td>SUBTOTAL</td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Charges</td><td align=right>" . CUR . " {$pur['shipping']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>VAT @ " . TAX_VAT . " %</td><td align=right>" . CUR . " {$pur['vat']}</td></tr>\n\t\t\t<tr class='bg-even'><th>GRAND TOTAL</th><td align=right>" . CUR . " {$TOTAL}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td align=right><input type=button value='&laquo Back' onClick='javascript:history.back()'> | <input type=submit name='upBtn' value='Write'></td></tr>\n\t</table></form>\n\t</center>";
    return $details;
}
function viewtran($_POST)
{
    extract($_POST);
    global $MONPRD, $PRDMON;
    require_lib("validate");
    $v = new validate();
    $v->isOk($accnt, "string", 1, 10, "Invalid Accounts Selection.");
    if ($accnt == 'slct') {
        if (isset($accids)) {
            foreach ($accids as $accid) {
                $v->isOk($accid, "num", 1, 20, "Invalid Account number.");
            }
        } else {
            return "<li class='err'>Please select at least one account.</li>" . slctacc();
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        return slct($err);
    }
    if ($accnt == 'all') {
        $accids = array();
        core_connect();
        $sql = "SELECT accid FROM accounts WHERE div = '" . USER_DIV . "'";
        $rs = db_exec($sql);
        while ($ac = pg_fetch_array($rs)) {
            $accids[] = $ac['accid'];
        }
    } else {
        if ($accnt == "allactive") {
            $accids = array();
            $sql = "SELECT accid FROM core.trial_bal\n\t\t\t\tWHERE (debit!=0 OR credit!=0) AND div='" . USER_DIV . "'\n\t\t\t\t\tAND period>='" . $MONPRD[$fprd] . "' AND period<='" . $MONPRD[$tprd] . "'\n\t\t\t\tGROUP BY accid";
            $qry = new dbSql($sql);
            $qry->run();
            while ($macc_data = $qry->fetch_array()) {
                $accids[] = $macc_data["accid"];
            }
        }
    }
    if ($key == "spreadsheet") {
        $pure = true;
    } else {
        $pure = false;
    }
    # Get all Closed Periods
    db_conn("audit");
    // $sql = "SELECT * FROM closedprd";
    // $clsRs = db_exec($sql) or errDie("Could not get closed periods from audit DB",SELF);
    $trans = "";
    $hide = "";
    //while($cls = pg_fetch_array($clsRs)){
    foreach ($accids as $key => $accid) {
        $accRs = get("core", "accname, accid, topacc, accnum", "accounts", "accid", $accid);
        $acc = pg_fetch_array($accRs);
        $sql = "SELECT debit,credit FROM core.trial_bal WHERE accid='{$accid}' AND month='{$tprd}'";
        $qry = new dbSql($sql);
        $qry->run();
        $tb = $qry->fetch_array();
        $tbbal = $tb["debit"] - $tb["credit"];
        $hide .= "<input type='hidden' name='accids[]' value='{$acc['accid']}'>";
        $trans .= "\n\t\t\t<tr>\n\t\t\t\t<th>&nbsp;</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Reference</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t\t<th>Balance</th>\n\t\t\t\t<th>Contra Acc</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='8'><b>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</b></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4' align='right'><b>Balance at end of " . getMonthName($tprd) . "</b></td>\n\t\t\t\t<td align='right'><b>" . money($tb["debit"]) . "</b></td>\n\t\t\t\t<td align='right'><b>" . money($tb["credit"]) . "</b></td>\n\t\t\t\t<td align='right' nowrap='t'><b>" . ($tbbal > 0 ? money($tbbal) . " DT" : money(-$tbbal) . " CT") . "</b></td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>";
        $cp = $fprd;
        $fs = 0;
        if ($fprd == $tprd + 1) {
            $f = true;
        } else {
            $f = false;
        }
        while ($cp != $tprd + 1 || $f) {
            $prd = $cp;
            $cp++;
            if ($cp == 13) {
                $cp = 1;
            }
            $fs++;
            if ($fs > 13) {
                break;
            }
            $f = false;
            # Period name
            $prdname = prdname($prd);
            $trans .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='8' align='center'><h3>{$prdname}</h3></td>\n\t\t\t\t</tr>";
            if (isset($t)) {
                unset($t);
            }
            # Get balances
            $idRs = get($prd, "max(id), min(id)", "ledger", "acc", $accid);
            $id = pg_fetch_array($idRs);
            if ($id['min'] != 0) {
                $balRs = get($prd, "(cbalance-credit) as cbalance,(dbalance-debit) as dbalance", "ledger", "id", $id['min']);
                $bal = pg_fetch_array($balRs);
                $cbalRs = get($prd, "cbalance,dbalance", "ledger", "id", $id['max']);
                $cbal = pg_fetch_array($cbalRs);
            } else {
                if (!isset($t)) {
                    $trans .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='8' align='center'><li> There are no transactions in this period.</td>\n\t\t\t\t\t\t</tr>";
                }
                continue;
                $balRs = get("core", "credit as cbalance, debit as dbalance", "trial_bal", "accid", $accid);
                $bal = pg_fetch_array($balRs);
                $cbal['cbalance'] = 0;
                $cbal['dbalance'] = 0;
            }
            $t = "lemme ci";
            if ($bal['dbalance'] > $bal['cbalance']) {
                $bal['dbalance'] = sprint($bal['dbalance'] - $bal['cbalance']);
                $bal['cbalance'] = "";
                $balance = $bal['dbalance'];
                $fl = "DT";
            } elseif ($bal['cbalance'] > $bal['dbalance']) {
                $bal['cbalance'] = sprint($bal['cbalance'] - $bal['dbalance']);
                $bal['dbalance'] = "";
                $balance = $bal['cbalance'];
                $fl = "CT";
            } else {
                $bal['cbalance'] = "";
                $bal['dbalance'] = "";
                $balance = "0.00";
                $fl = "";
            }
            $balance = sprint($balance);
            // calculate which year the current period is in
            $prd_y = getFinYear() - 1;
            if ($prd < $PRDMON[1]) {
                ++$prd_y;
            }
            // make the date of the last day of the previous prd
            $bbf_date = date("t-M-Y", mktime(0, 0, 0, $prd - 1, 1, $prd_y));
            $trans .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2' align='right'>{$bbf_date}</td>\n\t\t\t\t\t<td>Br/Forwd</td>\n\t\t\t\t\t<td>Brought Forward</td>\n\t\t\t\t\t<td align='right'>{$bal['dbalance']}</td>\n\t\t\t\t\t<td align='right'>{$bal['cbalance']}</td>\n\t\t\t\t\t<td align='right'>{$balance} {$fl}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            # --> transactio reding comes here <--- #
            $dbal['debit'] = 0;
            $dbal['credit'] = 0;
            $tranRs = get($prd, "*", "ledger", "acc", $accid);
            while ($tran = pg_fetch_array($tranRs)) {
                $dbal['debit'] += $tran['debit'];
                $dbal['credit'] += $tran['credit'];
                # Current(Running) balance
                if ($tran['dbalance'] > $tran['cbalance']) {
                    $tran['dbalance'] = sprint($tran['dbalance'] - $tran['cbalance']);
                    $tran['cbalance'] = "";
                    $cbalance = $tran['dbalance'];
                    $cfl = "DT";
                } elseif ($tran['cbalance'] > $tran['dbalance']) {
                    $tran['cbalance'] = sprint($tran['cbalance'] - $tran['dbalance']);
                    $tran['dbalance'] = "";
                    $cbalance = $tran['cbalance'];
                    $cfl = "CT";
                } else {
                    $tran['cbalance'] = "";
                    $tran['dbalance'] = "";
                    $cbalance = "0.00";
                    $cfl = "";
                }
                # Format date
                $tran['edate'] = explode("-", $tran['edate']);
                $tran['edate'] = $tran['edate'][2] . "-" . $tran['edate'][1] . "-" . $tran['edate'][0];
                $trans .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$tran['edate']}</td>\n\t\t\t\t\t\t<td>{$tran['eref']}</td>\n\t\t\t\t\t\t<td>{$tran['descript']}</td>\n\t\t\t\t\t\t<td align='right'>{$tran['debit']}</td>\n\t\t\t\t\t\t<td align='right'>{$tran['credit']}</td>\n\t\t\t\t\t\t<td align='right'>{$cbalance} {$cfl}</td>\n\t\t\t\t\t\t<td>{$tran['ctopacc']}/{$tran['caccnum']} - {$tran['caccname']}</td>\n\t\t\t\t\t</tr>";
            }
            # Total balance changes
            if ($dbal['debit'] > $dbal['credit']) {
                $dbal['debit'] = sprint($dbal['debit'] - $dbal['credit']);
                $dbal['credit'] = "";
            } elseif ($dbal['credit'] > $dbal['debit']) {
                $dbal['credit'] = sprint($dbal['credit'] - $dbal['debit']);
                $dbal['debit'] = "";
            } else {
                $dbal['credit'] = "";
                $dbal['debit'] = "0.00";
            }
            $trans .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t\t<td>A/C Total</td>\n\t\t\t\t\t<td>Total for period {$prdname}:</td>\n\t\t\t\t\t<td align='right'>{$dbal['debit']}</td>\n\t\t\t\t\t<td align='right'>{$dbal['credit']}</td>\n\t\t\t\t\t<td align='right'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
        }
        $trans .= "<tr><td colspan='8'><br></td></tr>";
    }
    $fprdname = prdname($fprd);
    $tprdname = prdname($tprd);
    $sp = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    $view = "";
    if (!$pure) {
        $view .= "\n\t\t\t<center>\n\t\t\t<h3>Period Range General Ledger</h3>\n\t\t\t<h4>{$fprdname} - {$tprdname}</h4>";
    }
    $view .= "<table " . TMPL_tblDflts . " width='90%'>";
    if (!$pure) {
        $view .= "\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='spreadsheet'>\n\t\t\t\t<input type='hidden' name='fprd' value='{$fprd}'>\n\t\t\t\t<input type='hidden' name='tprd' value='{$tprd}'>\n\t\t\t\t<input type='hidden' name='prd' value='{$prd}'>\n\t\t\t\t<input type='hidden' name='accnt' value='{$accnt}'>\n\t\t\t\t{$hide}\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='8' align='center'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t\t</tr>\n\t\t\t\t" . TBL_BR;
    }
    $view .= $trans;
    if (!$pure) {
        $view .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='8'>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='8' align='center'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t\t</tr>\n\t\t\t<table>\n\t\t\t</form>" . mkQuickLinks(ql("index-reports.php", "Financials"), ql("index-reports-journal.php", "Current Year Details General Ledger Reports"), ql("../core/acc-new2.php", "Add New Account"));
    }
    return $view;
}
function details($_POST, $error = "")
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid Non-Stock Invoice number.");
    } elseif (isset($cusnum)) {
        $v->isOk($cusnum, "num", 1, 20, "Invalid Customer number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slct($error);
        $confirm = "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($invid)) {
        $invid = create_dummy(0, $cusnum);
    }
    # 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);
    # check if invoice has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : invoice number <b>{$invid}</b> has already been printed</li>.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $currs = getSymbol($inv['fcid']);
    /* --- Start Drop Downs --- */
    # format date
    list($s_year, $s_month, $s_day) = explode("-", $inv['sdate']);
    # keep the charge vat option stable
    if ($inv['chrgvat'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnone = "";
    } elseif ($inv['chrgvat'] == "no") {
        $chy = "";
        $chn = "checked=yes";
        $chnone = "";
    } else {
        $chy = "";
        $chn = "";
        $chnone = "checked=yes";
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th colspan='2'>UNIT PRICE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>VAT Code</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $stkd['amt'] = round($stkd['amt'], 2);
        $chk = "";
        if ($stkd['vatex'] == 'y') {
            $chk = "checked=yes";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl);
        $vats = "<select name='vatcodes[]'>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatex'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $vats .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $vats .= "</option>";
        $stkd['amt'] = sprint($stkd['amt']);
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='50' name='des[]' value='{$stkd['description']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td align='center'> " . CUR . " <input type='text' size='8' name='cunitcost[]' value='{$stkd['cunitcost']}'></td>\n\t\t\t\t<td align='center'> {$inv['currency']} <input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> {$inv['currency']} {$stkd['amt']}</td>\n\t\t\t\t<td align='center'>{$vats}</td>\n\t\t\t\t<td align='center'><input type='checkbox' name='remprod[]' value='{$i}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t</tr>";
        $i++;
    }
    # Look above(remprod keys)
    $keyy = $i;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    if ($i == 0 || isset($diffwhBtn)) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl);
        $vats = "<select name='vatcodes[]'>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $vats .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $vats .= "</option>";
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='50' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'>" . CUR . " <input type='text' size='8' name='cunitcost[]'></td>\n\t\t\t\t<td align='center'>{$inv['currency']} <input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td>{$inv['currency']} 0.00</td>\n\t\t\t\t<td>{$vats}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $inv['subtot'];
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['tval']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    $cust = pg_fetch_array($custRslt);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $details = "\n\t\t<tr>\n\t\t\t<th colspan='2'> Customer Details </th>\n\t\t</tr>\n\t\t<input type='hidden' name='cusname' value='{$cust['cusname']} {$cust['surname']}'>\n\t\t<input type='hidden' name='cusaddr' value='{$cust['addr1']}'>\n\t\t<input type='hidden' name='cusvatno' value='{$cust['vatnum']}'>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Customer</td>\n\t\t\t<td valign='center'>{$cust['cusname']} {$cust['surname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Customer Address</td>\n\t\t\t<td valign='center'><pre>{$cust['addr1']}</pre></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Customer Vat Number</td>\n\t\t\t<td valign='center'>{$cust['vatnum']}</td>\n\t\t</tr>";
    if (isset($diffwhBtn) or isset($upBtn) or isset($doneBtn)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details = "\n\t\t<center>\n\t\t<h3>New International Non-Stock Invoice</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Invoice Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Non-Stock Invoice No.</td>\n\t\t\t\t\t\t\t<td valign='center'>TI {$inv['invid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Proforma Invoice No.</td>\n\t\t\t\t\t\t\t<td><input type='text' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center' nowrap='t'>" . mkDateSelect("s", $s_year, $s_month, $s_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Foreign Currency</td>\n\t\t\t\t\t\t\t<td valign='center'>{$currs['symbol']} - {$currs['name']} &nbsp;&nbsp;Exchange rate " . CUR . " <input type='text' size='7' name='xrate' value='{$inv['xrate']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='yes' {$chy}> No<input type='radio' size='7' name='chrgvat' value='no' {$chn}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$inv['remarks']}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['vat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name='diffwhBtn' type='submit' value='Add Item'> |</td>\n\t\t\t\t<td><input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($purid)) {
        $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Order number.");
    } else {
        $v->isOk($ctyp, "string", 0, 20, "Invalid purchase type.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($purid)) {
        $purid = create_dummy(0);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li class='err'>Purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($npur_year, $npur_month, $npur_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnv = "";
    } else {
        if ($pur['vatinc'] == 'novat') {
            $chy = "";
            $chn = "";
            $chnv = "checked=yes";
        } else {
            $chy = "";
            $chn = "checked=yes";
            $chnv = "";
        }
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>VAT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        $stkd['amt'] = round($stkd['amt'], 2);
        $tip = "&nbsp;&nbsp;&nbsp;";
        if (isset($vatc[$key])) {
            $tip = "<font color='red'>#</font>";
            $error = "<div class='err'> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; Vat amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatcode'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $stkd['amt'] = sprint($stkd['amt']);
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value='{$stkd['cod']}'></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value='{$stkd['des']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($i), $syear, $smon, $sday) . "</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t<td>{$tip} <input type='text' name='vat[]' size='9' value='{$stkd['svat']}'></td>\n\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
        if (isset($trans_date_setting) and $trans_date_setting == "yes") {
            $trans_date_value = getCSetting("TRANSACTION_DATE");
            $date_arr = explode("-", $trans_date_value);
            $item_year = $date_arr[0];
            $item_month = $date_arr[1];
            $item_day = $date_arr[2];
        } else {
            $item_year = date("Y");
            $item_month = date("m");
            $item_day = date("d");
        }
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($i), $item_year, $item_month, $item_day) . "</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td><input type='hidden' name='novat[]' value='1'></td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $j = $i + 1;
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t</td><td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($j)) . "</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td><input type='hidden' name='novat[{$j}]' value='1'></td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
        $key++;
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $pur['subtot'];
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    if ($pur['ctyp'] == "s") {
        db_connect();
        $sql = "SELECT * FROM suppliers WHERE location != 'int' AND div = '" . USER_DIV . "' ORDER BY supno ASC";
        $supRslt = db_exec($sql) or errDie("Could not retrieve Suppliers Information from the Database.", SELF);
        $sups = "<select name='supplier'>";
        if (pg_numrows($supRslt) < 1) {
            $sups .= "<option value='-S'></option>";
        }
        while ($sup = pg_fetch_array($supRslt)) {
            if ($sup['supid'] == $pur['supplier']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $sups .= "<option value='{$sup['supid']}' {$sel}>{$sup['supno']} {$sup['supname']}</option>";
        }
        $sups .= "</select>";
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td>{$sups}</td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='supaddr' value=''>";
    } elseif ($pur['ctyp'] == "cb") {
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "c") {
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Cash Order";
        }
        //Cash Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "p") {
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Petty Cash Order";
        }
        //Petty Cash Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "ac") {
        //<input type='text' name='supplier' value='$pur[supplier]'>
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Ledger Account Order";
        }
        //Ledger Account Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "c") {
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } else {
        return slct($_POST);
    }
    $pur['delvat'] += 0;
    if ($pur['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $pur['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $pur['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $ex = "";
    if (strlen($pur['supinv']) and $pur['ctyp'] == "s") {
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$pur['supplier']}' AND supinv='{$pur['supinv']}' AND purid != '{$purid}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
    }
    $Vatcodes .= "</select>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (!isset($supinv)) {
        $supinv = $pur['supinv'];
    }
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h3>New Non-Stock Order</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$sdata}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan=2> Non-Stock Order Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Non-Stock Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$ordernum}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Supplier Inv No</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='supinv' value='{$supinv}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("npur", $npur_year, $npur_month, $npur_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> No<input type='radio' size='7' name='vatinc' value='no' {$chn}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='shipchrg' value='{$pur['shipchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$ex} {$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purchase-view.php'>View Non-Stock Orders</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['shipping']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['vat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><input name='diffwhBtn' type='submit' value='Add Item'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t</center>";
    return $details;
}
function search($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purnum, "string", 1, 20, "Invalid Purchase number.");
    # display errors, if any
    $error = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class=err>" . $e["msg"];
        }
        return slct($_POST, $error);
    }
    $purs = explode(",", $purnum);
    foreach ($purs as $pur) {
        print $pur . "<br>";
    }
    # Send search squad
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($srchRslt) > 0) {
        $purid = create_dummy(0, $purnum, 'loc', 'cubit');
        $send['purid'] = $purid;
        return details($send);
    }
    $sql = "SELECT * FROM purch_int WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($srchRslt) > 0) {
        $purid = create_dummy(0, $purnum, 'int', 'cubit');
        $send['purid'] = $purid;
        return details($send);
    }
    $sql = "SELECT * FROM movpurch WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($srchRslt) > 0) {
        $res = pg_fetch_array($srchRslt);
        $purid = create_dummy(0, $purnum, $res['purtype'], $res['prd']);
        $send['purid'] = $purid;
        return details($send);
    }
    return slct($_POST, "<li class=err> - Purchase No. {$purnum} not found.");
}
function update($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($nincome_code, "string", 0, 5, "Invalid income code specified.");
    $v->isOk($nincome_description, "string", 0, 255, "Invalid income description.");
    $v->isOk($nincome_rfind, "string", 0, 60, "Invalid RF IND.");
    $v->isOk($nincome_amount, "string", 0, 9, "Invalid income amount.");
    $v->isOk($directive_number, "num", 0, 9, "Invalid directive number.");
    $v->isOk($over_deduction, "float", 0, 20, "Invalid over deduction.");
    if (isset($income_code)) {
        foreach ($income_code as $id => $value) {
            $v->isOk($income_code[$id], "string", 0, 5, "Invalid income code specified.");
            $v->isOk($income_description[$id], "string", 0, 255, "Invalid income description.");
            $v->isOk($income_rfind[$id], "string", 0, 60, "Invalid RF IND.");
            $v->isOk($income_amount[$id], "string", 0, 9, "Invalid income amount.");
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    // New income sources
    if ($nincome_code != 0 || !empty($nincome_description) || $nincome_rfind != "N" || !empty($nincome_amount)) {
        db_conn("cubit");
        $sql = "INSERT INTO emp_income_sources (empnum, code, description, rf_ind, amount) VALUES\n\t\t\t('{$empnum}', '{$nincome_code}', '{$nincome_description}', '{$nincome_rfind}', '{$nincome_amount}')";
        $rslt = db_exec($sql) or errDie("Unable to save income sources to Cubit.");
    }
    // Update old income sources
    if (isset($income_code)) {
        foreach ($income_code as $id => $value) {
            db_conn("cubit");
            $sql = "UPDATE emp_income_sources SET code='{$income_code[$id]}', description='{$income_description[$id]}', rf_ind='{$income_rfind[$id]}', amount='{$income_amount[$id]}' WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Unable to update income sources to Cubit.");
        }
    }
    // Anything to remove
    if (isset($income_rem)) {
        foreach ($income_rem as $id => $value) {
            db_conn("cubit");
            $sql = "DELETE FROM emp_income_sources WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Unable to remove selected items from Cubit.");
        }
    }
    // Where to go from here?
    if (isset($display)) {
        export($_POST);
    } else {
        return slct();
    }
}
function details($_POST, $error = "")
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    if (!isset($button) && isset($starting)) {
        return slct();
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid Non-Stock Invoice number.");
    } elseif (isset($ctyp)) {
        $val = $ctyp . "val";
        if (isset(${$val})) {
            $tval = ${$val};
            $v->isOk($tval, "num", 1, 20, "Invalid Selection.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class=err>" . $e["msg"];
        }
        return slct($error);
        $confirm = "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($invid) && isset($ctyp)) {
        $val = $ctyp . "val";
        if (!isset(${$val})) {
            ${$val} = "";
        }
        $tval = ${$val};
        if (isset($bankid)) {
            $bankid += 0;
            $acc = $bankid;
        } else {
            $acc = 0;
        }
        $invid = create_dummy(0, $ctyp, $tval, $acc);
    }
    # 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);
    # check if invoice 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;
    }
    /* --- Start Drop Downs --- */
    # format date
    list($ninv_year, $ninv_month, $ninv_day) = explode("-", $inv['odate']);
    # keep the charge vat option stable
    if ($inv['chrgvat'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnone = "";
    } elseif ($inv['chrgvat'] == "no") {
        $chy = "";
        $chn = "checked=yes";
        $chnone = "";
    } else {
        $chy = "";
        $chn = "";
        $chnone = "checked=yes";
    }
    # Days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\r\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=100%>\r\n\t<tr>\r\n\t\t<th>DESCRIPTION</th>\r\n\t\t<th>QTY</th>\r\n\t\t<th>AMOUNT</th>\r\n\t\t<th>VAT Code</th>\r\n\t\t<th>Remove</th>\r\n\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $stkd['amt'] = round($stkd['amt'], 2);
        $chk = "";
        if ($stkd['vatex'] == 'y') {
            $chk = "checked=yes";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl);
        $vats = "<select name=vatcodes[]>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatex'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $vats .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $vats .= "</option>";
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        $products .= "<tr class='bg-odd'>\r\n\t\t\t<td align=center><input type=text size=50 name=des[] value='{$stkd['description']}'></td>\r\n\t\t\t<td align=center><input type=text size=3 name=qtys[] value='{$stkd['qty']}'></td>\r\n\t\t\t<td><input type=hidden name=amt[] value='" . sprint($stkd["amt"]) . "'> " . CUR . " " . sprint($stkd["amt"]) . "</td>\r\n\t\t\t<!--<td align=center><input type=checkbox name=vatex[] value='{$i}' {$chk}></td>-->\r\n\t\t\t<td align=center>{$vats}</td>\r\n\t\t\t<td align=center><input type=checkbox name=remprod[] value='{$i}'><input type=hidden name=SCROLL value=yes></td>\r\n\t\t</tr>";
        $i++;
    }
    # Look above(remprod keys)
    $keyy = $i;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    # Get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class=err> There are no Sales People found in Cubit.";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    if ($i == 0 || isset($diffwhBtn)) {
        # add one
        $products .= "<tr class='bg-odd'>\r\n\t\t\t<td align=center><input type=text size=50 name=des[] value=''></td>\r\n\t\t\t<td align=center><input type=text size=3 name=qtys[] value='1'></td>\r\n\t\t\t<td>" . CUR . " 0.00</td>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $inv['subtot'];
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    db_conn('cubit');
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['tval']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cust = pg_fetch_array($custRslt);
        if (!empty($cust["cusname"])) {
            $cn = "{$cust['cusname']} {$cust['surname']}";
        } else {
            $cn = "{$cust['surname']}";
        }
        $details = "\r\n\t\t<tr><th colspan=2> Customer Details </th></tr>\r\n\t\t<input type=hidden name=cusname value='{$cn}'>\r\n\t\t<input type=hidden name=cusaddr value='{$cust['addr1']}'>\r\n\t\t<input type=hidden name=cusvatno value='{$cust['vatnum']}'>\r\n\t\t<tr class='bg-odd'><td>Customer</td><td valign=center>{$cust['cusname']} {$cust['surname']}</td></tr>\r\n\t\t<tr class='bg-even'><td>Customer Address</td><td valign=center><pre>{$cust['addr1']}</pre></td></tr>\r\n\t\t<tr class='bg-odd'><td>Customer VAT Number</td><td valign=center>{$cust['vatnum']}</td></tr>";
    } elseif ($inv['ctyp'] == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['tval']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t<tr><th colspan=2> Customer Details </th></tr>\r\n\t\t<tr class='bg-odd'><td>Customer</td><td valign=middle><input type=text name=cusname value='{$inv['cusname']}'></td></tr>\r\n\t\t<tr class='bg-even'><td valign=top>Customer Address</td><td valign=middle><textarea name=cusaddr cols=18 rows=3>{$inv['cusaddr']}</textarea></td></tr>\r\n\t\t<tr class='bg-odd'><td valign=top>Customer VAT No.</td><td valign=middle><input type=text name=cusvatno value='{$inv['cusvatno']}'></td></tr>";
    } else {
        $details = "\r\n\t\t<tr><th colspan=2> Customer Details </th></tr>\r\n\t\t<tr class='bg-odd'><td>Customer</td><td valign=middle><input type=text name=cusname value='{$inv['cusname']}'></td></tr>\r\n\t\t<tr class='bg-even'><td valign=top>Customer Address</td><td valign=middle><textarea name=cusaddr cols=18 rows=3>{$inv['cusaddr']}</textarea></td></tr>\r\n\t\t<tr class='bg-odd'><td valign=top>Customer VAT No.</td><td valign=middle><input type=text name=cusvatno value='{$inv['cusvatno']}'></td></tr>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "<td>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t<tr><td>{$salesps}</td><td>Print</td><td><input type=checkbox name=printsales {$sc}></td></tr>\r\n\t</table>\r\n\t</td>";
    // Retrieve the default comments
    db_conn("cubit");
    $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
    $cmntRslt = db_exec($sql) or errDie("Unable to retrieve default comment from Cubit.");
    if (empty($inv["remarks"])) {
        $remarks = base64_decode(pg_fetch_result($cmntRslt, 0));
    } else {
        $remarks = $inv["remarks"];
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $deldate = explode("-", $inv["deldate"]);
    /* -- Final Layout -- */
    $details = "<center><h3>New Non-Stock Invoices</h3>\r\n\t<form action='" . SELF . "' method=post name=form>\r\n\t<input type=hidden name=key value=update>\r\n\t<input type=hidden name=invid value='{$invid}'>\r\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=95%>\r\n \t<tr><td valign=top>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\r\n\t\t\t{$details}\r\n\t\t\t<tr class='bg-even'><td>Customer Order number</td><td valign=center><input type=text size=10 name=cordno value='{$inv['cordno']}'></td></tr>\r\n\t\t</table>\r\n\t</td>\r\n\t<td valign=top align=right>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t<tr>\r\n\t\t<th colspan='2'>Non-Stock Invoice Details</th>\r\n\t</tr>\r\n\t<tr class='bg-odd'>\r\n\t\t<td>Non-Stock Invoice No.</td>\r\n\t\t<td valign=center>TI {$inv['invid']}</td>\r\n\t</tr>\r\n\t<tr class='bg-even'>\r\n\t\t<td>Proforma Invoice No.</td>\r\n\t\t<td><input type='text' name='docref' value='{$inv['docref']}'></td>\r\n\t</tr>\r\n\t<tr class='bg-odd'>\r\n\t\t<td>Date</td>\r\n\t\t<td valign='center'>" . mkDateSelect("ninv", $ninv_year, $ninv_month, $ninv_day) . " DD-MM-YYYY</td>\r\n\t</tr>\r\n\t<tr class='bg-even'>\r\n\t\t<td>VAT Inclusive</td>\r\n\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='yes' {$chy}> No<input type=radio size=7 name=chrgvat value='no' {$chn}></td>\r\n\t</tr>\r\n\t<tr class='bg-odd'>\r\n\t\t<td>Terms</td>\r\n\t\t<td valign='center'>{$termssel} Days</td>\r\n\t</tr>\r\n\t<tr class='bg-even'>\r\n\t\t<td>Sales Person</td>\r\n\t\t{$sales}\r\n\t</tr>\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=2>{$products}</td></tr>\r\n\t<tr><td>\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t<tr><th width=25%>Quick Links</th><th width=25%>Remarks</th><td rowspan=5 valign=top width=50%>{$error}</td></tr>\r\n\t\t\t<tr><td class='bg-odd'><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td><td class='bg-odd' rowspan=4 align=center valign=top><textarea name=remarks rows=4 cols=20>{$remarks}</textarea></td></tr>\r\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t</table>\r\n\t</td><td align=right>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=80%>\r\n\t\t\t<tr class='bg-odd'><td>SUBTOTAL</td><td align=right>" . CUR . " <input type=hidden name=subtot value='{$SUBTOT}'>{$SUBTOT}</td></tr>\r\n\t\t\t<tr class='bg-odd'><td>VAT {$vat14}</td><td align=right>" . CUR . " {$inv['vat']}</td></tr>\r\n\t\t\t<tr class='bg-even'><th>GRAND TOTAL</th><td align=right>" . CUR . " <input type=hidden name=total value='{$TOTAL}'>{$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td align=right><input name=diffwhBtn type=submit value='Add Item'> |</td><td><input type=submit name='upBtn' value='Update'>{$done}</td></tr>\r\n\t</table></form>\r\n\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    if (!isset($button) && isset($starting)) {
        return slct();
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid Non-Stock Invoice number.");
    } elseif (isset($ctyp)) {
        $val = $ctyp . "val";
        if (isset(${$val})) {
            $tval = ${$val};
            $v->isOk($tval, "num", 1, 20, "Invalid Selection.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slct($error);
        $confirm = "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($invid) && isset($ctyp)) {
        $val = $ctyp . "val";
        if (!isset(${$val})) {
            ${$val} = "";
        }
        $tval = ${$val};
        if (isset($bankid)) {
            $bankid += 0;
            $acc = $bankid;
        } else {
            $acc = 0;
        }
        // Retrieve default comments
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve default comments from Cubit.");
        $comment = base64_decode(pg_fetch_result($commRslt, 0));
        $invid = create_dummy(0, $ctyp, $tval, $acc, $comment);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM rnons_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);
    /* --- Start Drop Downs --- */
    # format date
    list($rinv_year, $rinv_month, $rinv_day) = explode("-", $inv['sdate']);
    # keep the charge vat option stable
    if ($inv['chrgvat'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnone = "";
    } elseif ($inv['chrgvat'] == "no") {
        $chy = "";
        $chn = "checked=yes";
        $chnone = "";
    } else {
        $chy = "";
        $chn = "";
        $chnone = "checked=yes";
    }
    # Days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Account</th>\n\t\t\t\t<th>VAT Code</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM rnons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $stkd['amt'] = round($stkd['amt'], 2);
        $chk = "";
        if ($stkd['vatex'] == 'y') {
            $chk = "checked=yes";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl);
        $vats = "<select name='vatcodes[]'>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatex'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $vats .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $vats .= "</select>";
        db_conn('core');
        $Sl = "SELECT accid,accname FROM accounts WHERE div='" . USER_DIV . "' ORDER BY accname";
        $Ri = db_exec($Sl);
        $accounts = "<select name='accounts[]'>";
        while ($ad = pg_fetch_array($Ri)) {
            if (isb($ad['accid'])) {
                continue;
            }
            if ($ad['accid'] == $stkd['account']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
        }
        $accounts .= "</select>";
        db_conn('cubit');
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='50' name='des[]' value='{$stkd['description']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " " . sprint($stkd["amt"]) . "</td>\n\t\t\t\t<td>{$accounts}</td>\n\t\t\t\t<td align='center'>{$vats}</td>\n\t\t\t\t<td align='center'><input type='checkbox' name='remprod[]' value='{$i}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t</tr>";
        $i++;
    }
    # Look above(remprod keys)
    $keyy = $i;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    if ($i == 0 || isset($diffwhBtn)) {
        db_conn('core');
        $Sl = "SELECT accid,accname FROM accounts WHERE div='" . USER_DIV . "' ORDER BY accname";
        $Ri = db_exec($Sl);
        $accounts = "<select name='accounts[]'>";
        while ($ad = pg_fetch_array($Ri)) {
            if (isb($ad['accid'])) {
                continue;
            }
            $accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
        }
        $accounts .= "</select>";
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='50' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td>{$accounts}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $inv['subtot'];
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    db_conn('cubit');
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['tval']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cust = pg_fetch_array($custRslt);
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='cusname' value='{$cust['surname']}'>\n\t\t\t<input type='hidden' name='cusaddr' value='{$cust['addr1']}'>\n\t\t\t<input type='hidden' name='cusvatno' value='{$cust['vatnum']}'>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'>{$cust['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer Address</td>\n\t\t\t\t<td valign='center'><pre>{$cust['addr1']}</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer Vat Number</td>\n\t\t\t\t<td valign='center'>{$cust['vatnum']}</td>\n\t\t\t</tr>";
    } elseif ($inv['ctyp'] == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['tval']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'><input type='text' name='cusname' value='{$inv['cusname']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t<td valign='center'><textarea name='cusaddr' cols='18' rows='3'>{$inv['cusaddr']}</textarea></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer VAT No.</td>\n\t\t\t\t<td valign='center'><input type='text' name='cusvatno' value='{$inv['cusvatno']}'></td>\n\t\t\t</tr>";
    } else {
        db_conn('core');
        $Sl = "SELECT accid,accname FROM accounts WHERE div='" . USER_DIV . "' ORDER BY accname";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $accountss = "<select name=account>";
        while ($ad = pg_fetch_array($Ri)) {
            if ($ad['accid'] == $inv['tval']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $accountss .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
        }
        $accountss .= "</select>";
        $details = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'><input type='text' name='cusname' value='{$inv['cusname']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t<td valign='center'><textarea name='cusaddr' cols='18' rows='3'>{$inv['cusaddr']}</textarea></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Customer VAT No.</td>\n\t\t\t\t<td valign='center'><input type='text' name='cusvatno' value='{$inv['cusvatno']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Ledger Account</td>\n\t\t\t\t<td>{$accountss}</td>\n\t\t\t</tr>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $ctd = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cost Center</th>\n\t\t\t\t\t<th>Percentage</th>\n\t\t\t\t</tr>";
        $i = 0;
        while ($data = pg_fetch_array($Ri)) {
            $Sl = "SELECT * FROM ninvc WHERE inv='{$invid}' AND cid='{$data['ccid']}'";
            $Rq = db_exec($Sl);
            $cd = pg_fetch_array($Rq);
            $ctd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$data['centername']}</td>\n\t\t\t\t\t<td><input type='text' name='ct[{$data['ccid']}]' size='5' value='{$cd['amount']}'>%</td>\n\t\t\t\t</tr>";
            $i++;
        }
        $ctd .= "</table>";
    } else {
        $ctd = "";
    }
    if (empty($inv["remarks"])) {
        // Retrieve default comments
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve default comments from Cubit.");
        $comment = base64_decode(pg_fetch_result($commRslt, 0));
    } else {
        $comment = $inv["remarks"];
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (isset($diffwhBtn) or isset($upBtn) or isset($doneBtn)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details = "\n\t\t<center>\n\t\t<h3>New Recurring Non-Stock Invoices</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Invoice Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Recurring Non-Stock Invoice No.</td>\n\t\t\t\t\t\t\t<td valign='center'>RI {$inv['invid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Proforma Invoice No.</td>\n\t\t\t\t\t\t\t<td><input type='text' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("rinv", $rinv_year, $rinv_month, $rinv_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='yes' {$chy}> No<input type='radio' size='7' name='chrgvat' value='no' {$chn}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$ctd}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='rec-nons-invoice-view.php'>View Recurring Non-Stock Invoices</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$comment}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['vat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input name='diffwhBtn' type='submit' value='Add Item'> |</td>\n\t\t\t\t<td><input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Purchase number.");
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return slct($_POST, "<li class='err'>No Non Stock Purchase Found</li>");
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("0" => "0", "7" => "7", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($lnpur_year, $lnpur_month, $lnpur_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnv = "";
    } else {
        if ($pur['vatinc'] == 'novat') {
            $chy = "";
            $chn = "";
            $chnv = "checked=yes";
        } else {
            $chy = "";
            $chn = "checked=yes";
            $chnv = "";
        }
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t<th>VAT</th>\n\t\t\t\t\t\t\t<th>Remove</th>\n\t\t\t\t\t\t<tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($d_year, $d_month, $d_day) = explode("-", $stkd['ddate']);
        $stkd['amt'] = round($stkd['amt'], 2);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatcode'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $stkd['amt'] = sprint($stkd['amt']);
        # put in product
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value='{$stkd['cod']}'></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value='{$stkd['des']}'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", $key, $d_year, $d_month, $d_day) . "</td>\n\t\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t\t\t<td><input type='text' name='vat[]' size='9' value='{$stkd['svat']}'></td>\n\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        # add one
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", 0) . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='novat[]' value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>";
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", $key) . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='novat[{$key}]' value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>";
        $key++;
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $pur['subtot'];
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>New Non-Stock Purchase</h3>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t\t\t\t\t<input type='hidden' name='shipchrg' value='0'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t\t \t<tr>\n\t\t\t\t\t \t\t<td valign='top'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Purchase Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Linked Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['spurnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Non-Stock Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$ordernum}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("lnpur", $lnpur_year, $lnpur_month, $lnpur_day) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> No<input type='radio' size='7' name='vatinc' value='no' {$chn}></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purchase-view.php'>View Non-Stock Purchases</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['vat']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name='diffwhBtn' type='submit' value='Add Item'> |</td>\n\t\t\t\t\t\t\t<td><input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</form>\n\t\t\t\t\t</center>";
    return $details;
}
        case "view":
            $OUTPUT = printStmnt($_POST);
            break;
        default:
            # decide what to do
            if (isset($_GET["cusnum"])) {
                $OUTPUT = slct($_GET);
            } else {
                $OUTPUT = "<li class=err>Invalid use of module.";
            }
            break;
    }
} else {
    # decide what to do
    if (isset($_GET["cusnum"])) {
        $OUTPUT = slct($_GET);
    } else {
        $OUTPUT = "<li class='err'>Invalid use of module.</li>";
    }
}
require "template.php";
# Default view
function slct($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer number.");
    # display errors, if any
Example #16
0
function display($_POST)
{
    extract($_POST);
    global $PRDMON;
    #determine the date range based on period selection
    if (isset($year_to_process)) {
        switch ($year_to_process) {
            case "active":
                $fdate_year = getYearOfFinPrd(1);
                $fdate_month = $PRDMON[1];
                $fdate_day = "1";
                $tdate_year = getYearOfFinPrd(12);
                $tdate_month = $PRDMON[12];
                $tdate_day = date("d", mktime(0, 0, 0, $PRDMON[12] + 1, 0, $tdate_year));
                break;
            case "previous":
                $fdate_year = getYearOfFinPrd(1) - 1;
                $fdate_month = $PRDMON[1];
                $fdate_day = "1";
                $tdate_year = getYearOfFinPrd(12) - 1;
                $tdate_month = $PRDMON[12];
                $tdate_day = date("d", mktime(0, 0, 0, $PRDMON[12] + 1, 0, $tdate_year));
                break;
            default:
                $fdate_year = getYearOfFinPrd(1);
                $fdate_month = "03";
                $fdate_day = "01";
                $tdate_year = getYearOfFinPrd(12);
                $tdate_month = "02";
                $tdate_day = date("d", mktime(0, 0, 0, 3, 0, $tdate_year));
        }
    }
    // -----------------------------------------------------------------------
    // Sanity checks
    // -----------------------------------------------------------------------
    require_lib("validate");
    $v = new validate();
    // Does this employee number actually exist
    db_conn("cubit");
    $sql = "SELECT * FROM employees WHERE empnum='" . (int) $empnum . "' AND div='" . USER_DIV . "'";
    $empinf_rslt = db_exec($sql) or errDie("Unable to retrieve employee number from Cubit.");
    if (pg_num_rows($empinf_rslt) == 0) {
        $v->addError(0, "Employee number not found in Cubit.");
    }
    $v->isOk($fdate_month, "num", 1, 2, "Invalid from date (month)");
    $v->isOk($fdate_year, "num", 4, 4, "Invalid from date (year)");
    $v->isOk($tdate_month, "num", 1, 2, "Invalid to date (month)");
    $v->isOk($tdate_year, "num", 4, 4, "Invalid to date (year)");
    if ($fdate_month > 12) {
        $v->addError(0, "Invalid from date (month)");
    }
    if ($fdate_year < 1970 || $fdate_year > 2050) {
        $v->addError(0, "Invalid from date (year)");
    }
    if ($tdate_month > 12) {
        $v->addError(0, "Invalid to date (month)");
    }
    if ($tdate_year < 1970 || $tdate_year > 2050) {
        $v->addError(0, "Invalid to date (year)");
    }
    if ($fdate_day > getDaysInMonth((int) $fdate_month, $fdate_year)) {
        $v->addError(0, "Invalid from date (day)");
    }
    if ($tdate_day > getDaysInMonth((int) $tdate_month, $tdate_year)) {
        $v->addError(0, "Invalid to date (day)");
    }
    $from_time = mktime(0, 0, 0, $fdate_day, $fdate_month, $fdate_year);
    $to_time = mktime(0, 0, 0, $tdate_day, $tdate_month, $tdate_year);
    if ($from_time > $to_time) {
        $v->addError(0, "Invalid date range specified.");
    }
    if (isset($income_code)) {
        foreach ($income_code as $id => $value) {
            $v->isOk($income_code[$id], "numeric", 1, 4, "Invalid income code.");
            $v->isOk($income_description[$id], "string", 1, 80, "Invalid income description.");
            $v->isOk($income_rfind[$id], "string", 1, 30, "Invalid RF IND.");
            $v->isOk($income_amount[$id], "float", 1, 9, "Invalid income amount.");
        }
    }
    // Return the errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $from_date = "{$fdate_year}-{$fdate_month}-{$fdate_day}";
    $to_date = "{$tdate_year}-{$tdate_month}-{$tdate_day}";
    $gross_taxable_annual_payments = 0.0;
    $gross_non_taxable_income = 0.0;
    $gross_retirement_funding_income = 0.0;
    $gross_non_retirement_funding_income = 0.0;
    $gross_remuneration = 0.0;
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $compinfo_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $compinfo = pg_fetch_array($compinfo_rslt);
    db_conn("cubit");
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}'";
    $empinfo_rslt = db_exec($sql) or errDie("Unable to retrieve employee information from Cubit.");
    $empinfo = pg_fetch_array($empinfo_rslt);
    $header_out = "<b>Return of payment for work & services from which no employees tax was deducted</b>";
    $employer_trading_name_out = array(array("<b>Trading or other name:</b> {$compinfo['compname']}"));
    $employer_irp5_number_out = array(array("<b>IT 3(a) number:</b> {$irp5_number}"));
    $employer_reference_number_out = array(array("<b>Reference number:</b> {$empinfo['taxref']}"));
    $employer_tax_year_out = array(array("<b>Tax year:</b> {$fdate_year}"));
    $employer_diplomatic_indemnity_out = array(array("<b>Diplomatic indemnity:</b> {$compinfo['diplomatic_indemnity']}"));
    $employer_business_address_out = array(array("<b>Employer business address:</b>"), array("{$compinfo['addr1']}"), array("{$compinfo['addr2']}"), array("{$compinfo['addr3']}"));
    $employer_postal_code_out = array(array("col1" => "<b>Postal Code:</b>", "col2" => "{$compinfo['addr4']}"));
    $employer_postal_code_cols = array("col1" => array("width" => 200, "justification" => "right"), "col2" => array("width" => 40, "justification" => "right"));
    // Extract the employee's birth date from her id number
    $bd_year = 1900 + substr($empinfo["idnum"], 0, 2);
    $bd_month = substr($empinfo["idnum"], 2, 2);
    $bd_day = substr($empinfo["idnum"], 4, 2);
    $employee_nature_out = array(array("<b>Nature of Person:</b> {$empinfo['nature']}"));
    $employee_surname_out = array(array("<b>Employee surname or trading name:</b> {$empinfo['sname']}"));
    $employee_first_names_out = array(array("<b>First two names:</b> {$empinfo['fnames']}"));
    $fnames = explode(" ", $empinfo["fnames"]);
    $initials = "";
    foreach ($fnames as $name) {
        $initials .= strtoupper($name[0]);
    }
    $employee_initials_out = array(array("<b>Initials:</b> {$initials}"));
    $employee_identity_number_out = array(array("<b>Identity number:</b> {$empinfo['idnum']}"));
    $employee_passport_number_out = array(array("<b>Passport number:</b> {$empinfo['passport_number']}"));
    $employee_date_of_birth_out = array(array("<b>Date of birth:</b> {$bd_year}-{$bd_month}-{$bd_day}"));
    $employee_cc_number_out = array(array("<b>Company/CC/Trust number:</b> {$empinfo['cc_number']}"));
    $employee_tax_number_out = array(array("<b>Income Tax number:</b> {$empinfo['tax_number']}"));
    $employee_residential_out = array(array("<b>Employees residential address:</b>"), array("{$empinfo['res1']}"), array("{$empinfo['res2']}"), array("{$empinfo['res3']}"));
    $employee_postal_code_out = array(array("col1" => "<b>Postal Code:</b>", "col2" => "{$empinfo['res4']}"));
    $employee_postal_code_cols = array("col1" => array("width" => 200, "justification" => "right"), "col2" => array("width" => 40, "justification" => "right"));
    $employee_number_out = array(array("<b>Employee Number:</b> {$empinfo['empnum']}"));
    $tax_prd_employed_frm_out = array(array("<b>Period employed from:</b> {$prd_employed_frm}"));
    $tax_prd_employed_to_out = array(array("<b>Period employed to:</b> {$prd_employed_to}"));
    $tax_directive_number_out = array(array("<b>Directive number:</b> {$directive_number}"));
    // Income sources --------------------------------------------------------
    $income_sources_out = array();
    $income_taxable_total = 0;
    $income_reimburse_total = 0;
    $income_travelallowance_total = 0;
    $income_subsis_total = 0;
    $income_otherallowance_total = 0;
    $deduction_motorcar_total = 0;
    db_conn("cubit");
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description='Basic Salary'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_taxable_total += $empinc_data["amount"];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3601", "<b>DESCRIPTION</b>" => "Income Taxable", "<b>RF IND</b>" => "N", "<b>AMOUNT</b>" => (int) $income_taxable_total);
    #handle travel allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description = 'Travel Allowance' AND type = 'INCT'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_travelallowance_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3701", "<b>DESCRIPTION</b>" => "Travel Allowance", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_travelallowance_total);
    #handle reimbursements ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description!='Basic Salary' AND ex = 'RBS'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_reimburse_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3702", "<b>DESCRIPTION</b>" => "Reimbursements", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_reimburse_total);
    #handle subsistance allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description != 'Basic Salary' AND ex = 'SUBS' AND type = '2'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_subsis_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3704", "<b>DESCRIPTION</b>" => "Subsistance Allowance", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_subsis_total);
    #handle other allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description != 'Basic Salary' AND description != 'Travel Allowance' AND ex != 'SUBS' AND ex != 'RBS' AND type = '2'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_otherallowance_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3713", "<b>DESCRIPTION</b>" => "Other Allowances", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_otherallowance_total);
    #handle motorcar DEDUCTIONS in income table ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND (description = 'Motorcar 1 Contribution for Use' OR description = 'Motorcar 2 Contribution for Use') AND (type = 'DEDA' OR type = 'DEDB')";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $deduction_motorcar_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3802", "<b>DESCRIPTION</b>" => "Use Of Motor Vehicle", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_motorcar_total);
    if (!empty($nincome_code) || !empty($nincome_description) || !empty($nincome_rfind) || !empty($nincome_amount)) {
        $income_sources_out[] = array("<b>CODE</b>" => "{$nincome_code}", "<b>DESCRIPTION</b>" => "{$nincome_description}", "<b>RF IND</b>" => "{$nincome_rfind}", "<b>AMOUNT</b>" => (int) $nincome_amount);
    }
    if (isset($income_code)) {
        foreach ($income_code as $id => $value) {
            if ($income_code[$id] != 0) {
                $income_sources_out[] = array("<b>CODE</b>" => "{$income_code[$id]}", "<b>DESCRIPTION</b>" => "{$income_description[$id]}", "<b>RF IND</b>" => "{$income_rfind[$id]}", "<b>AMOUNT</b>" => (int) $income_amount[$id]);
            } else {
                $income_sources_out[] = array("<b>CODE</b>" => "", "<b>DESCRIPTION</b>" => "", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => "");
            }
        }
    }
    $income_sources_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 340), "<b>RF IND</b>" => array("width" => 70), "<b>AMOUNT</b>" => array("width" => 70));
    // Gross renumeration ----------------------------------------------------
    // Taxable annual payments
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE code='3695' AND emp = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve taxable annual payments from Cubit.");
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_taxable_annual_payments += $emp_inc_data["amount"];
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE code='3695' AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve taxable annual payments from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        $gross_taxable_annual_payments += $emp_income_sources_data["amount"];
    }
    // Non taxable annual payments
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE (code='3602' OR code='3604' OR code='3612' OR code='3703' OR code='3705' OR code='3709' OR code='3714') AND emp = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve non taxable payments from Cubit.");
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_non_taxable_income += $emp_inc_data["amount"];
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE (code='3602' OR code='3604' OR code='3612' OR code='3703' OR code='3705' OR code='3709' OR code='3714') AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve non taxable payments from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        $gross_non_taxable_income += $emp_income_sources_data["amount"];
    }
    // Gross retirement funding income
    db_conn("cubit");
    $sql = "SELECT emp_pension, emp_ret FROM employees WHERE empnum='{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross retrirement funding from Cubit.");
    $emp_data = pg_fetch_array($rslt);
    $gross_retirement_funding_income += $gross_non_taxable_income / 100 * $emp_data["emp_pension"] + $emp_data["emp_ret"];
    // Gross non retirement funding income
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE (code!='3603' OR code!='3604' OR code!='3610' OR code!='3615') AND emp = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross non retirement funding from Cubit.");
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_non_retirement_funding_income += $emp_inc_data["amount"];
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE (code != '3603' OR code != '3604' OR code != '3610' OR code != '3615') AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross non retirement funding from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        $gross_non_retirement_funding_income += $emp_income_sources_data["amount"];
    }
    // Gross Remuneration
    $gross_remuneration = $gross_retirement_funding_income + $gross_non_retirement_funding_income;
    $gross_remuneration_out = array(array("<b>CODE</b>" => "3696", "<b>DESCRIPTION</b>" => "GROSS NON-TAXABLE INCOME", "<b>AMOUNT</b>" => (int) $gross_non_taxable_income), array("<b>CODE</b>" => "3697", "<b>DESCRIPTION</b>" => "GROSS RETIREMENT FUNDING INCOME", "<b>AMOUNT</b>" => (int) $gross_retirement_funding_income), array("<b>CODE</b>" => "3698", "<b>DESCRIPTION</b>" => "GROSS NON-RETIREMENT FUNDING INCOME", "<b>AMOUNT</b>" => (int) $gross_non_retirement_funding_income), array("<b>CODE</b>" => "3699", "<b>DESCRIPTION</b>" => "GROSS REMUNERATION", "<b>AMOUNT</b>" => (int) $gross_remuneration));
    $gross_remuneration_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 410), "<b>AMOUNT</b>" => array("width" => 70));
    // Deductions ------------------------------------------------------------
    $deductions_out = array();
    $deduction_pension_total = 0;
    $deduction_provident_total = 0;
    $deduction_medicalaid_total = 0;
    $deduction_retirementann_total = 0;
    $deduction_premiumpol_total = 0;
    db_conn("cubit");
    #handle pension deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Pension' AND type = 'DEDP'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_pension_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4001", "<b>DESCRIPTION</b>" => "Current pension fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_pension_total);
    #handle provident deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Provident' AND type = 'DEDV'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_provident_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4003", "<b>DESCRIPTION</b>" => "Current provident fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_provident_total);
    #handle retirement annuity deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Retirement Annuity Fund' AND type = 'DEDR'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_retirementann_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4006", "<b>DESCRIPTION</b>" => "Current retirement annuity fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_retirementann_total);
    $sql = "SELECT * FROM emp_ded WHERE emp='{$empnum}' AND description!='UIF' AND description!='SDL' AND description!='PAYE' AND description!='Motorcar 1 Contribution for Use' AND description!='Motorcar 2 Contribution for Use' AND description!='Medical Contribution' AND description!='Pension' AND description!='Provident' AND description!='Retirement Annuity Fund'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_premiumpol_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4018", "<b>DESCRIPTION</b>" => "Premiums paid on loss of income policies", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_premiumpol_total);
    //	db_conn("cubit");
    //	$sql = "SELECT * FROM empdeduct WHERE empnum='$empnum'";
    //	$empded_rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.'");
    //
    //	while ($empded_data = pg_fetch_array($empded_rslt)) {
    //		db_conn("cubit");
    //		$sql = "SELECT deduction, code FROM salded WHERE id='$empded_data[dedid]'";
    //		$rslt = db_exec($sql) or errDie("Unable to retrieve deduction information from Cubit.");
    //		$ded_data = pg_fetch_array($rslt);
    //
    //		$deductions_out[] = array (
    //			"<b>CODE</b>"=>"$ded_data[code]",
    //			"<b>DESCRIPTION</b>"=>"$ded_data[deduction]",
    //			"<b>CLEARANCE NO</b>"=>"$empded_data[clearance_no]",
    //			"<b>AMOUNT</b>"=>(int)$empded_data["amount"], 2
    //		);
    //	}
    if (!isset($deductions_out[0])) {
        $deductions_out = array(array("<b>CODE</b>" => "", "<b>DESCRIPTION</b>" => "", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => ""));
    }
    $deductions_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 340), "<b>CLEARANCE NO</b>" => array("width" => 70), "<b>AMOUNT</b>" => array("width" => 70));
    // Employees Tax deductions-----------------------------------------------
    $site_amount = 0;
    // Retrieve PAYE amount from Cubit
    db_conn("cubit");
    $sql = "SELECT * FROM emp_ded WHERE type='PAYE' AND emp = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve PAYE deductions from Cubit");
    $paye_amount = 0;
    while ($empded_data = pg_fetch_array($rslt)) {
        $paye_amount += $empded_data["amount"];
    }
    // Total tax deductions
    $tax_deductions_amount = $site_amount + $paye_amount;
    $non_deduction_of_tax_out = array(array("<b>CODE</b>" => "01", "<b>DESCRIPTION</b>" => "DIRECTORS REMUNERATION - PRIVATE COMPANY / CC"), array("<b>CODE</b>" => "02", "<b>DESCRIPTION</b>" => "LESS THAN THE TAX THRESHOLD"), array("<b>CODE</b>" => "03", "<b>DESCRIPTION</b>" => "INDEPENDENT CONTRACTOR"), array("<b>CODE</b>" => "04", "<b>DESCRIPTION</b>" => "NON TAXABLE EARNINGS"));
    $non_deduction_of_tax_cols = array("<b>CODE</b>" => array("width" => 40));
    if (!isset($reason_code)) {
        $reason_code = "";
    }
    $reason_out = array(array("{$reason_code}"));
    // -----------------------------------------------------------------------
    // Do the actual rendering of the pdf
    // -----------------------------------------------------------------------
    $pdf =& new Cezpdf();
    global $set_mainFont;
    $pdf->selectFont($set_mainFont);
    $pdf->addInfo("Title", "IT 3(a) for {$empinfo['fnames']} {$empinfo['sname']}");
    $pdf->addInfo("Author", USER_NAME);
    $irp5_pos = drawText(&$pdf, "<b>IT 3(a)</b>", 14, 520 - $pdf->getTextWidth(14, "<b>IT 3(a)</b>"), 0);
    $header_pos = drawText(&$pdf, $header_out, 10, 520 - $pdf->getTextWidth(10, $header_out), $irp5_pos['y'] + 14);
    // Employer information --------------------------------------------------
    $employer_information_head = drawText(&$pdf, "<b>EMPLOYER INFORMATION</b>", 8, 0, $irp5_pos['y'] + 14);
    $employer_trading_name_pos = drawTable2(&$pdf, $employer_trading_name_out, 0, $employer_information_head['y'] + 2, 520, 1);
    $employer_irp5_number_pos = drawTable2(&$pdf, $employer_irp5_number_out, 0, $employer_trading_name_pos['y'], 260, 1);
    $employer_reference_number_pos = drawTable2(&$pdf, $employer_reference_number_out, 0, $employer_irp5_number_pos['y'], 260, 1);
    $employer_tax_year_pos = drawTable2(&$pdf, $employer_tax_year_out, 0, $employer_reference_number_pos['y'], 260, 1);
    $employer_diplomatic_indemnity_pos = drawTable2(&$pdf, $employer_diplomatic_indemnity_out, 0, $employer_tax_year_pos['y'], 260, 1);
    $employer_business_address_pos = drawTable2(&$pdf, $employer_business_address_out, $employer_irp5_number_pos['x'] + 20, $employer_trading_name_pos['y'], 240, 4);
    $employer_postal_code_pos = drawTable2(&$pdf, $employer_postal_code_out, $employer_irp5_number_pos['x'] + 20, $employer_business_address_pos['y'], 240, 1, $employer_postal_code_cols);
    // Employee information --------------------------------------------------
    $employee_information_head = drawText(&$pdf, "<b>EMPLOYEE INFORMATION</b>", 8, 0, $employer_postal_code_pos['y'] + 15);
    $employee_nature_pos = drawTable2(&$pdf, $employee_nature_out, 0, $employee_information_head['y'], 100, 1);
    $employee_surname_pos = drawTable2(&$pdf, $employee_surname_out, $employee_nature_pos['x'] + 20, $employee_information_head['y'], 400, 1);
    $employee_first_names_pos = drawTable2(&$pdf, $employee_first_names_out, 0, $employee_nature_pos['y'], 400, 1);
    $employee_initials_pos = drawTable2(&$pdf, $employee_initials_out, $employee_first_names_pos['x'] + 20, $employee_nature_pos['y'], 100, 1);
    $employee_identity_number_pos = drawTable2(&$pdf, $employee_identity_number_out, 0, $employee_first_names_pos['y'], 260, 1);
    $employee_residential_pos = drawTable2(&$pdf, $employee_residential_out, $employee_identity_number_pos['x'] + 20, $employee_first_names_pos['y'], 240, 4);
    $employee_postal_code_pos = drawTable2(&$pdf, $employee_postal_code_out, $employee_identity_number_pos['x'] + 20, $employee_residential_pos['y'], 240, 1, $employee_postal_code_cols);
    $employee_number_pos = drawTable2(&$pdf, $employee_number_out, $employee_identity_number_pos['x'] + 20, $employee_postal_code_pos['y'], 240, 1);
    $employee_passport_number_pos = drawTable2(&$pdf, $employee_passport_number_out, 0, $employee_identity_number_pos['y'], 260, 1);
    $employee_date_of_birth_pos = drawTable2(&$pdf, $employee_date_of_birth_out, 0, $employee_passport_number_pos['y'], 260, 1);
    $employee_cc_number_pos = drawTable2(&$pdf, $employee_cc_number_out, 0, $employee_date_of_birth_pos['y'], 260, 1);
    $employee_tax_number_pos = drawTable2(&$pdf, $employee_tax_number_out, 0, $employee_cc_number_pos['y'], 260, 1);
    // Tax calculation information -------------------------------------------
    $tax_calculation_head = drawText(&$pdf, "<b>TAX CALCULATION INFORMATION</b>", 8, 0, $employee_number_pos['y'] + 15);
    $tax_prd_employed_frm_pos = drawTable2(&$pdf, $tax_prd_employed_frm_out, 0, $tax_calculation_head['y'], 160, 1);
    $tax_prd_employed_to_pos = drawTable2(&$pdf, $tax_prd_employed_to_out, $tax_prd_employed_frm_pos['x'] + 20, $tax_calculation_head['y'], 160, 1);
    drawTable2(&$pdf, $tax_directive_number_out, $tax_prd_employed_to_pos['x'] + 20, $tax_calculation_head['y'], 160, 1);
    // Income sources --------------------------------------------------------
    $income_sources_head = drawText(&$pdf, "<b>INCOME SOURCE</b>", 8, 0, $tax_prd_employed_frm_pos['y'] + 15);
    $income_sources_pos = drawTable2(&$pdf, $income_sources_out, 0, $income_sources_head['y'] + 2, 520, 20, $income_sources_cols, 1);
    $gross_remuneration_head = drawText(&$pdf, "<b>GROSS REMUNERATION</b>", 8, 0, $income_sources_pos['y'] + 15);
    $gross_remuneration_pos = drawTable2(&$pdf, $gross_remuneration_out, 0, $gross_remuneration_head['y'] + 2, 520, 4, $gross_remuneration_cols, 1);
    $deductions_head = drawText(&$pdf, "<b>DEDUCTIONS</b>", 8, 0, $gross_remuneration_pos['y'] + 15);
    $deductions_pos = drawTable2(&$pdf, $deductions_out, 0, $deductions_head['y'] + 2, 520, 15, $deductions_cols, 1);
    $non_deduction_of_tax_head = drawText(&$pdf, "<b>REASON FOR NON DEDUCTION OF EMPLOYEES TAX MUST BE STATED</b>", 8, 0, $deductions_pos['y'] + 15);
    $non_deduction_of_tax_pos = drawTable2(&$pdf, $non_deduction_of_tax_out, 0, $non_deduction_of_tax_head['y'] + 2, 420, 4, $non_deduction_of_tax_cols, 1);
    $reason_text = drawText(&$pdf, "<b>Reason Code</b>", 7, $non_deduction_of_tax_pos['x'] + 10, $non_deduction_of_tax_pos['y']);
    $reason_pos = drawTable2(&$pdf, $reason_out, $reason_text['x'] + 15, $non_deduction_of_tax_pos['y'] - 10, 40, 1);
    // Footer note -----------------------------------------------------------
    $certificate_attatch = drawText(&$pdf, "Attach this copy to your form IT 3", 6, 0, $non_deduction_of_tax_pos['y'] + 10);
    $pdf->ezStream();
}
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 printInvoice($_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;
    }
    # Set up table to display in
    $printOrd = "\r\n\t\t<center>\r\n\t\t<h3>View Recurring Non-Stock Invoices</h3>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t<form action='nons-rec-invoice-proc.php' method='GET'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Num</th>\r\n\t\t\t\t<th>Date</th>\r\n\t\t\t\t<th>Customer</th>\r\n\t\t\t\t<th>Total</th>\r\n\t\t\t\t<th colspan='5'>Options</th>\r\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $sql = "SELECT * FROM rnons_invoices WHERE typ = 'inv' AND sdate >= '{$fromdate}' AND sdate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        return slct("<li class='err'>No non stock recurring invoices found.</li><br>");
    }
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        # date format
        $date = explode("-", $nonstks['sdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        // compute the totals
        $tot_subtot += $nonstks["subtot"];
        $tot_total += $nonstks["total"];
        # calculate the Sub-Total
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        $det = "rec-nons-invoice-det.php";
        $edit = "rec-nons-invoice-new.php";
        $print = "nons-invoice-print.php";
        $reprint = "nons-invoice-reprint.php";
        $reprpdf = "nons-invoice-pdf-reprint.php";
        $note = "nons-invoice-note.php";
        $cur = CUR;
        if (isset($selnum) and $counter < 1000) {
            $ch = "checked";
        } else {
            if (isset($all)) {
                $ch = "checked";
            } else {
                $ch = "";
            }
        }
        $printOrd .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$nonstks['invnum']}</td>\r\n\t\t\t\t<td>{$date}</td>\r\n\t\t\t\t<td>{$nonstks['cusname']}</td>\r\n\t\t\t\t<td align='right'>{$cur} {$nonstks['total']}</td>\r\n\t\t\t\t<td><a href='{$det}?invid={$nonstks['invid']}'>Details</a></td>";
        if ($nonstks['done'] != "y" && $nonstks["subtot"] == 0) {
            $printOrd .= "\r\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\r\n\t\t\t\t\t<td><a href='rec-nons-invoice-rem.php?invid={$nonstks['invid']}'>Delete</a></td>\r\n\t\t\t\t\t<td><input type=checkbox name='invids[]' value='{$nonstks['invid']}' {$ch}></td>\r\n\t\t\t\t</tr>";
        } elseif ($nonstks['done'] != "y") {
            $printOrd .= "\r\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\r\n\t\t\t\t\t<td><a href='rec-nons-invoice-rem.php?invid={$nonstks['invid']}'>Delete</a></td>\r\n\t\t\t\t\t<td><input type='checkbox' name='invids[]' value='{$nonstks['invid']}' {$ch}></td>\r\n\t\t\t\t</tr>";
        } else {
            $cn = "";
            if ($nonstks['balance'] != 0) {
                $cn = "<a href='#' onClick=printer('{$note}?invid={$nonstks['invid']}')>Credit Note</a>";
            }
            $printOrd .= "\r\n\t\t\t\t\t<td>{$cn}</td>\r\n\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$nonstks['invid']}'>Reprint</a></td>\r\n\t\t\t\t\t<td><a href='pdf/{$reprpdf}?invid={$nonstks['invid']}' target='_blank'>Reprint in PDF</a></td>\r\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$nonstks['invid']}]' {$ch}></td>\r\n\t\t\t\t</tr>";
        }
        $i++;
    }
    $tot_total = sprint($tot_total);
    $printOrd .= "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='3'>Totals: {$i}</td>\r\n\t\t\t<td align='right'>" . CUR . " {$tot_total}</td>\r\n\t\t\t<td colspan='6' align='right'><input type='submit' name='edit' value='Edit Item Prices On Selected'> <input type='submit' value='Process Selected'></td>\r\n\t\t</tr>";
    $printOrd .= "\r\n\t\t<tr><td><br></td></tr></form>\r\n\t\t<form action='" . SELF . "' method='POST'>\r\n\t\t\t<input type='hidden' name='key' value='view'>\r\n\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\r\n\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\r\n\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\r\n\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\r\n\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\r\n\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\r\n\t\t\t<input type='hidden' name='all' value=''>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td colspan='6'></td>\r\n\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>\r\n\t\t\t</tr>\r\n\t\t</form>";
    $printOrd .= "\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr><td><br></td></tr>\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='rec-nons-invoice-new.php'>New Recurring Non-Stock Invoice</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 $printOrd;
}
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 cdetails($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    if (!isset($button) && isset($starting)) {
        return slct($_GET);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    # 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'>{$err}";
        return $confirm;
    }
    if ($ctyp == "ac") {
        return acdetails($_GET);
    }
    # 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 invoices information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $details = "";
    if ($ctyp == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cust = pg_fetch_array($custRslt);
        $details = "\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<input type='hidden' name='cusnum' value='{$cusnum}'>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$cust['cusname']} {$cust['surname']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'><pre>{$cust['addr1']}</pre></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$cust['vatnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>";
    } elseif ($ctyp == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<input type='hidden' name='deptid' value='{$deptid}'>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusname']} </td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>";
    } elseif ($ctyp == 'cb') {
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Bank not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = "{$dept['bankname']} - {$dept['accname']}({$dept['acctype']})";
        }
        $details = "\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<input type='hidden' name='bankid' value='{$inv['accid']}'>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusname']} </td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Account</td>\r\n\t\t\t\t\t\t\t\t<td>{$supacc}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>";
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "\r\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th width='5%'>#</th>\r\n\t\t\t\t\t\t\t<th width='55%'>DESCRIPTION</th>\r\n\t\t\t\t\t\t\t<th width='10%'>QTY</th>\r\n\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\r\n\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\r\n\t\t\t\t\t\t\t<th width='10%'>ACCOUNT</th>\r\n\t\t\t\t\t\t<tr>";
    # get selected stock in this Invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $i++;
        // Check Tax Excempt
        db_conn("cubit");
        $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $zRslt = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
        $vatex = pg_fetch_result($zRslt, 0);
        if ($vatex == "Yes") {
            $ex = "#";
        } else {
            $ex = "";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $stkacc = "";
        core_connect();
        $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY accname ASC";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.</li>";
        }
        while ($acc = pg_fetch_array($accRslt)) {
            if (isb($acc['accid'])) {
                continue;
            }
            if ($acc["accid"] == $stkd["accid"]) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $stkacc .= "<option value='{$acc['accid']}' {$sel}>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</option>";
        }
        $stkacc .= "</select>";
        # put in product
        $products .= "\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td align='center'>{$i}</td>\r\n\t\t\t\t\t\t\t<td>{$ex} {$stkd['description']}</td>\r\n\t\t\t\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t\t\t\t<td>{$stkd['unitcost']}</td>\r\n\t\t\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['amt']}</td>\r\n\t\t\t\t\t\t\t<td " . ass("Select the account you wish to Credit") . "><select name='stkaccs[{$stkd['id']}]'>{$stkacc}</td>\r\n\t\t\t\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    # format date
    list($syear, $smon, $sday) = explode("-", $inv['odate']);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\r\n\t<center>\r\n\t<h3>Non-Stock Invoice Details</h3>\r\n\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t<input type='hidden' name='key' value='cconfirm'>\r\n\t<input type='hidden' name='invid' value={$invid}>\r\n\t<input type='hidden' name='ctyp' value={$ctyp}>\r\n\t<table " . TMPL_tblDflts . " width=95%>\r\n\t<tr><td valign='top'>\r\n\t\t{$details}\r\n\t</td><td valign='top' align='right'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr><th colspan='2'> Non-Stock Invoice Details </th></tr>\r\n\t\t\t<tr class='bg-odd'><td>Non-Stock Invoice No.</td><td valign='center'>T {$inv['invid']}</td></tr>\r\n\t\t\t<tr class='bg-even'><td>Proforma Inv No.</td><td valign='center'>{$inv['docref']}</td></tr>\r\n\t\t\t<tr class='bg-odd'><td>Date</td><td valign='center'>{$sday}-{$smon}-{$syear}</td></tr>\r\n\t\t\t<tr class='bg-even'><td>VAT Inclusive</td><td valign='center'>{$inv['chrgvat']}</td></tr>\r\n\t\t\t<tr class='bg-odd'><td>Terms</td><td valign='center'>{$inv['terms']} Days</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan='2'>\r\n\t{$products}\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr><th width='40%'>Quick Links</th><th width='45%'>Remarks</th><td rowspan='5' valign='top' width='15%'><br></td></tr>\r\n\t\t\t<tr class='bg-odd'><td align='center'><a href='nons-invoice-new.php'>New Non-Stock Invoices</a></td><td class='bg-odd' rowspan=4 align=center valign=top>" . nl2br($inv['remarks']) . "</td></tr>\r\n\t\t\t<tr class='bg-odd'><td align='center'><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td></tr>\r\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t</table>\r\n\t</td><td align='right'>\r\n\t\t<table " . TMPL_tblDflts . " width='80%'>\r\n\t\t\t<tr class='bg-odd'><td>SUBTOTAL</td><td align='right'>" . CUR . " {$inv['subtot']}</td></tr>\r\n\t\t\t<tr class='bg-odd'><td>VAT {$vat14}</td><td align='right'>" . CUR . " {$inv['vat']}</td></tr>\r\n\t\t\t<tr class='bg-even'><th>GRAND TOTAL</th><td align='right'>" . CUR . " {$inv['total']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td align='right'><input type='submit' value='Confirm &raquo'></td></tr>\r\n\t</table></form>\r\n\t</center>";
    return $details;
}
function update($_POST)
{
    extract($_POST);
    // Validate
    require_lib("validate");
    $v = new validate();
    if (isset($accid) && isset($category)) {
        $v->isOk($accid, "num", 1, 9, "Invalid account selection.");
        $v->isOk($category, "string", 1, 6, "Invalid category selection.");
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $key = strtolower($key);
    if ($key == "add" || $key == "select account") {
        // Make sure the account has not been added already
        db_conn("cubit");
        $sql = "SELECT * FROM saved_cf_accounts WHERE accid='{$accid}'";
        $cfacc_rslt = db_exec($sql) or errDie("Unable to retrieve account from the account list.");
        if (!pg_num_rows($cfacc_rslt)) {
            db_conn("cubit");
            $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('{$accid}', '{$category}')";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to save account to the accounts list.");
        }
    }
    if ($key == "remove selected") {
        if (!isset($rem)) {
            $rem = array();
        }
        foreach ($rem as $id) {
            db_conn("cubit");
            $sql = "DELETE FROM saved_cf_accounts WHERE accid='{$id}'";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to remove selected account from the accounts list.");
        }
    }
    if ($key == "default") {
        list($accid) = qryAccountsName("Depreciation", "accid");
        db_conn("cubit");
        $cols = grp(m("accid", $accid), m("category", "nciis"));
        $qry = new dbUpdate("saved_cf_accounts", "cubit", $cols);
        $qry->run(DB_INSERT);
        // add balance sheet items to list
        $qry = new dbQuery(DB_SQL, "INSERT INTO cubit.saved_cf_accounts (accid, category)\n\t\t\tSELECT accid, 'ciaal' FROM core.accounts WHERE catid='B10'");
        $qry->run();
        /*
        // Inventory
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Inventory'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the inventory account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the inventory account.");
        
        // Accounts Receivable
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Customer Control Account'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the accounts receivable account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the accounts receivable account.");
        */
    }
    return slct();
}
function display($_POST)
{
    extract($_POST);
    global $PRDMON;
    #determine the date range based on period selection
    if (isset($year_to_process)) {
        switch ($year_to_process) {
            case "active":
                $fdate_year = getYearOfFinPrd(1);
                $fdate_month = $PRDMON[1];
                $fdate_day = "1";
                $tdate_year = getYearOfFinPrd(12);
                $tdate_month = $PRDMON[12];
                $tdate_day = date("d", mktime(0, 0, 0, $PRDMON[12] + 1, 0, $tdate_year));
                break;
            case "previous":
                $fdate_year = getYearOfFinPrd(1) - 1;
                $fdate_month = $PRDMON[1];
                $fdate_day = "1";
                $tdate_year = getYearOfFinPrd(12) - 1;
                $tdate_month = $PRDMON[12];
                $tdate_day = date("d", mktime(0, 0, 0, $PRDMON[12] + 1, 0, $tdate_year));
                break;
            default:
                $fdate_year = getYearOfFinPrd(1);
                $fdate_month = "03";
                $fdate_day = "01";
                $tdate_year = getYearOfFinPrd(12);
                $tdate_month = "02";
                $tdate_day = date("d", mktime(0, 0, 0, 3, 0, $tdate_year));
        }
    }
    // -----------------------------------------------------------------------
    // Sanity checks
    // -----------------------------------------------------------------------
    require_lib("validate");
    $v = new validate();
    // Does this employee number actually exist
    db_conn("cubit");
    $sql = "SELECT * FROM employees WHERE empnum='" . (int) $empnum . "' AND div='" . USER_DIV . "'";
    $empinf_rslt = db_exec($sql) or errDie("Unable to retrieve employee number from Cubit.");
    if (pg_num_rows($empinf_rslt) == 0) {
        $v->addError(0, "Employee number not found in Cubit.");
    }
    $v->isOk($fdate_month, "num", 1, 2, "Invalid from date (month)");
    $v->isOk($fdate_year, "num", 4, 4, "Invalid from date (year)");
    $v->isOk($tdate_month, "num", 1, 2, "Invalid to date (month)");
    $v->isOk($tdate_year, "num", 4, 4, "Invalid to date (year)");
    if ($fdate_month > 12) {
        $v->addError(0, "Invalid from date (month)");
    }
    if ($fdate_year < 1970 || $fdate_year > 2050) {
        $v->addError(0, "Invalid from date (year)");
    }
    if ($tdate_month > 12) {
        $v->addError(0, "Invalid to date (month)");
    }
    if ($tdate_year < 1970 || $tdate_year > 2050) {
        $v->addError(0, "Invalid to date (year)");
    }
    if ($fdate_day > getDaysInMonth((int) $fdate_month, $fdate_year)) {
        $v->addError(0, "Invalid from date (day)");
    }
    if ($tdate_day > getDaysInMonth((int) $tdate_month, $tdate_year)) {
        $v->addError(0, "Invalid to date (day)");
    }
    $from_time = mktime(0, 0, 0, $fdate_day, $fdate_month, $fdate_year);
    $to_time = mktime(0, 0, 0, $tdate_day, $tdate_month, $tdate_year);
    if ($from_time > $to_time) {
        $v->addError(0, "Invalid date range specified.");
    }
    // Return the errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $from_date = "{$fdate_year}-{$fdate_month}-{$fdate_day}";
    $to_date = "{$tdate_year}-{$tdate_month}-{$tdate_day}";
    $gross_taxable_annual_payments = 0.0;
    $gross_non_taxable_income = 0.0;
    $gross_retirement_funding_income = 0.0;
    $gross_non_retirement_funding_income = 0.0;
    $gross_remuneration = 0.0;
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $compinfo_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $compinfo = pg_fetch_array($compinfo_rslt);
    db_conn("cubit");
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}'";
    $empinfo_rslt = db_exec($sql) or errDie("Unable to retrieve employee information from Cubit.");
    $empinfo = pg_fetch_array($empinfo_rslt);
    $header_out = "<b>Employees tax certificate</b>";
    $employer_trading_name_out = array(array("<b>Trading or other name:</b> {$compinfo['compname']}"));
    $employer_irp5_number_out = array(array("<b>IRP 5 number:</b> {$irp5_number}"));
    $employer_reference_number_out = array(array("<b>Reference number:</b> {$empinfo['taxref']}"));
    $employer_tax_year_out = array(array("<b>Tax year:</b> " . ($fdate_year + 1)));
    $employer_diplomatic_indemnity_out = array(array("<b>Diplomatic indemnity:</b> {$compinfo['diplomatic_indemnity']}"));
    $employer_business_address_out = array(array("<b>Employer business address:</b>"), array("{$compinfo['addr1']}"), array("{$compinfo['addr2']}"), array("{$compinfo['addr3']}"));
    $employer_postal_code_out = array(array("col1" => "<b>Postal Code:</b>", "col2" => "{$compinfo['addr4']}"));
    $employer_postal_code_cols = array("col1" => array("width" => 200, "justification" => "right"), "col2" => array("width" => 40, "justification" => "right"));
    // Extract the employee's birth date from her id number
    $bd_year = 1900 + substr($empinfo["idnum"], 0, 2);
    $bd_month = substr($empinfo["idnum"], 2, 2);
    $bd_day = substr($empinfo["idnum"], 4, 2);
    // Period employed from
    // strip out the dashes from the date
    $prd_employed_frm = explode("-", $empinfo["hiredate"]);
    $prd_employed_frm = implode($prd_employed_frm);
    // Period employed to
    if (empty($empinfo["firedate"])) {
        $prd_employed_to = getFinYear() . "0228";
    } else {
        $prd_employed_to = explode("-", $firedate);
        $prd_employed_to = implode("", $prd_employed_to);
    }
    $employee_nature_out = array(array("<b>Nature of Person:</b> {$empinfo['nature']}"));
    $employee_surname_out = array(array("<b>Employee surname or trading name:</b> {$empinfo['sname']}"));
    $employee_first_names_out = array(array("<b>First two names:</b> {$empinfo['fnames']}"));
    $fnames = explode(" ", $empinfo["fnames"]);
    $initials = "";
    foreach ($fnames as $name) {
        $initials .= strtoupper($name[0]);
    }
    $employee_initials_out = array(array("<b>Initials:</b> {$initials}"));
    $employee_identity_number_out = array(array("<b>Identity number:</b> {$empinfo['idnum']}"));
    $employee_passport_number_out = array(array("<b>Passport number:</b> {$empinfo['passport_number']}"));
    $employee_date_of_birth_out = array(array("<b>Date of birth:</b> {$bd_year}-{$bd_month}-{$bd_day}"));
    $employee_cc_number_out = array(array("<b>Company/CC/Trust number:</b> {$empinfo['cc_number']}"));
    $employee_tax_number_out = array(array("<b>Income Tax number:</b> {$empinfo['tax_number']}"));
    $employee_residential_out = array(array("<b>Employees residential address:</b>"), array("{$empinfo['res1']}"), array("{$empinfo['res2']}"), array("{$empinfo['res3']}"));
    $employee_postal_code_out = array(array("col1" => "<b>Postal Code:</b>", "col2" => "{$empinfo['res4']}"));
    $employee_postal_code_cols = array("col1" => array("width" => 200, "justification" => "right"), "col2" => array("width" => 40, "justification" => "right"));
    $employee_number_out = array(array("<b>Employee Number:</b> {$empinfo['empnum']}"));
    $tax_prd_employed_frm_out = array(array("<b>Period employed from:</b> {$prd_employed_frm}"));
    $tax_prd_employed_to_out = array(array("<b>Period employed to:</b> {$prd_employed_to}"));
    $tax_over_deduction_out = array(array("<b>Voluntary over-deduction:</b> {$over_deduction}"));
    switch ($empinfo["payprd"]) {
        case "m":
            $pay_periods = 12;
            break;
        case "f":
            $pay_periods = 24;
            break;
        case "w":
            $pay_periods = 48;
            break;
    }
    $tax_prd_in_year_out = array(array("<b>Pay periods in year:</b> {$pay_periods}"));
    if ($year_to_process == "active") {
        $cyear = EMP_YEAR;
    } else {
        $cyear = EMP_YEAR - 1;
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE emp='{$empinfo['empnum']}' AND description='Basic Salary' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve the number of periods worked from Cubit.");
    $pay_periods_worked = pg_num_rows($rslt);
    $tax_prd_worked_out = array(array("<b>Number of periods worked:</b> {$pay_periods_worked}"));
    $tax_fixed_rate_income_out = array(array("<b>Fixed rate income:</b> {$empinfo['fixed_rate']}"));
    $tax_directive_number_out = array(array("<b>Directive number:</b> {$directive_number}"));
    // Income sources --------------------------------------------------------
    $income_sources_out = array();
    $income_taxable_total = 0;
    $income_commission_total = 0;
    $income_bonus_total = 0;
    $income_reimburse_total = 0;
    $income_travelallowance_total = 0;
    $income_subsis_total = 0;
    $income_otherallowance_total = 0;
    $deduction_motorcar_total = 0;
    $deduction_medical_total = 0;
    //	$deduction_medicalaid_total = 0;
    db_conn("cubit");
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description='Basic Salary' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_taxable_total += $empinc_data["amount"];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3601", "<b>DESCRIPTION</b>" => "Income Taxable", "<b>RF IND</b>" => "N", "<b>AMOUNT</b>" => (int) $income_taxable_total);
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description='Bonus' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_bonus_total += $empinc_data["amount"];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3605", "<b>DESCRIPTION</b>" => "Bonus", "<b>RF IND</b>" => "N", "<b>AMOUNT</b>" => (int) $income_bonus_total);
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description='Commission' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_commission_total += $empinc_data["amount"];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3606", "<b>DESCRIPTION</b>" => "Commission", "<b>RF IND</b>" => "N", "<b>AMOUNT</b>" => (int) $income_commission_total);
    #handle travel allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description = 'Travel Allowance' AND type = 'INCT' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_travelallowance_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3701", "<b>DESCRIPTION</b>" => "Travel Allowance", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_travelallowance_total);
    #handle reimbursements ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description!='Basic Salary' AND ex = 'RBS' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_reimburse_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3702", "<b>DESCRIPTION</b>" => "Reimbursements", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_reimburse_total);
    #handle subsistance allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description != 'Basic Salary' AND ex = 'SUBS' AND type = '2' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_subsis_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3704", "<b>DESCRIPTION</b>" => "Subsistance Allowance", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_subsis_total);
    #handle other allowances ....
    $sql = "SELECT amount FROM emp_inc WHERE emp='{$empnum}' AND description != 'Basic Salary' AND description != 'Travel Allowance' AND ex != 'SUBS' AND ex != 'RBS' AND type = '2' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $income_otherallowance_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3713", "<b>DESCRIPTION</b>" => "Other Allowances", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $income_otherallowance_total);
    #handle motorcar DEDUCTIONS in income table ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND (description = 'Motorcar 1 Contribution for Use' OR description = 'Motorcar 2 Contribution for Use') AND (type = 'DEDA' OR type = 'DEDB') AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $deduction_motorcar_total += $empinc_data['amount'];
    }
    $income_sources_out[] = array("<b>CODE</b>" => "3802", "<b>DESCRIPTION</b>" => "Use Of Motor Vehicle", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_motorcar_total);
    #handle medical DEDUCTIONS in income table ...
    //$sql = "SELECT amount FROM emp_com WHERE emp='$empnum' AND description = 'Medical Contribution' AND type = 'DEDM'";
    $sql = "SELECT amount FROM emp_com WHERE emp='{$empnum}' AND description = 'Medical Contribution' AND type = 'COMM' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $deduction_medical_total += $empinc_data['amount'];
    }
    //"<b>CODE</b>" => "3816",
    $income_sources_out[] = array("<b>CODE</b>" => "3810", "<b>DESCRIPTION</b>" => "Medical Contribution", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_medical_total);
    #handle medical aid DEDUCTIONS in income table ...
    //	$sql = "SELECT amount FROM emp_ded WHERE emp='$empnum' AND description = 'Medical Contribution' AND type = 'DEDM'";
    //	$rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    //	while ($empinc_data = pg_fetch_array($rslt)) {
    //		$deduction_medicalaid_total += $empinc_data['amount'];
    //	}
    //	$income_sources_out[] = array (
    //		"<b>CODE</b>" => "3802",
    //		"<b>DESCRIPTION</b>" => "Medical aid contributions",
    //		"<b>RF IND</b>" => "",
    //		"<b>AMOUNT</b>" => (int)$deduction_medicalaid_total
    //	);
    // old
    //	$sql = "SELECT * FROM emp_inc WHERE emp='$empnum' AND description!='Basic Salary'";
    //	$rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    //	while ($empinc_data = pg_fetch_array($rslt)) {
    //		$income_sources_out[] = array (
    //			"<b>CODE</b>"=>"$empinc_data[code]",
    //			"<b>DESCRIPTION</b>"=>"$empinc_data[description]",
    //			"<b>RF IND</b>"=>"",
    //			"<b>AMOUNT</b>"=>(int)$empinc_data["amount"]
    //		);
    //	}
    if (!empty($nincome_description) || !empty($nincome_amount) && $nincome_code != 0) {
        $income_sources_out[] = array("<b>CODE</b>" => "{$nincome_code}", "<b>DESCRIPTION</b>" => "{$nincome_description}", "<b>RF IND</b>" => "{$nincome_rfind}", "<b>AMOUNT</b>" => (int) $nincome_amount);
    }
    if (isset($income_code)) {
        foreach ($income_code as $id => $value) {
            if ($income_code[$id] != 0) {
                $income_sources_out[] = array("<b>CODE</b>" => "{$income_code[$id]}", "<b>DESCRIPTION</b>" => "{$income_description[$id]}", "<b>RF IND</b>" => "{$income_rfind[$id]}", "<b>AMOUNT</b>" => (int) $income_amount[$id]);
            } else {
                $income_sources_out[] = array("<b>CODE</b>" => "", "<b>DESCRIPTION</b>" => "", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => "");
            }
        }
    }
    $income_sources_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 340), "<b>RF IND</b>" => array("width" => 70), "<b>AMOUNT</b>" => array("width" => 70));
    // Gross renumeration ----------------------------------------------------
    // Taxable annual payments
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE (code='3695' OR code='3601' OR description='Bonus') AND emp = '{$empnum}' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve taxable annual payments from Cubit.");
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_taxable_annual_payments += $emp_inc_data["amount"];
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE (code='3695' OR code='3601') AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve taxable annual payments from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        $gross_taxable_annual_payments += $emp_income_sources_data["amount"];
    }
    // Non taxable annual payments
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE (code='3602' OR code='3604' OR code='3612' OR code='3703' OR code='3705' OR code='3709' OR code='3714') AND emp = '{$empnum}' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve non taxable payments from Cubit.");
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_non_taxable_income += $emp_inc_data["amount"];
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE (code='3602' OR code='3604' OR code='3612' OR code='3703' OR code='3705' OR code='3709' OR code='3714') AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve non taxable payments from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        if ($emp_income_sources_data["rf_ind"] == "Y") {
            $gross_non_taxable_income += $emp_income_sources_data["amount"];
        }
    }
    // Gross retirement funding income
    db_conn("cubit");
    $sql = "SELECT emp_pension, emp_ret FROM employees WHERE empnum='{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross retrirement funding from Cubit.");
    $emp_data = pg_fetch_array($rslt);
    // RF IND
    $rfind_y = 0;
    if (isset($income_rfind)) {
        foreach ($income_rfind as $id => $value) {
            if ($income_rfind[$id] == "Y") {
                $rfind_y += $income_amount[$id];
            }
        }
    }
    //wth emp_pension is a PERCENTAGE, not some amount to add
    //	$gross_retirement_funding_income += $emp_data["emp_pension"] + $emp_data["emp_ret"] + $rfind_y;
    $gross_retirement_funding_income += $gross_taxable_annual_payments / 100 * $emp_data["emp_pension"] + $emp_data["emp_ret"] + $rfind_y;
    // Gross non retirement funding income
    db_conn("cubit");
    $sql = "SELECT * FROM emp_inc WHERE ((code != '3601' AND code != '3603' AND code != '3604' AND code != '3610' AND code != '3615') OR description = 'Basic Salary') AND emp = '{$empnum}' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross non retirement funding from Cubit.");
    // RF IND
    $rfind_n = 0;
    if (isset($income_rfind)) {
        foreach ($income_rfind as $id => $value) {
            if ($income_rfind[$id] == "N") {
                $rfind_n += $income_amount[$id];
            }
        }
    }
    while ($emp_inc_data = pg_fetch_array($rslt)) {
        $gross_non_retirement_funding_income += $emp_inc_data["amount"] + $rfind_n;
    }
    db_conn("cubit");
    $sql = "SELECT * FROM emp_income_sources WHERE (code != '3601' AND code != '3603' AND code != '3604' AND code != '3610' AND code!='3615') AND empnum = '{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve gross non retirement funding from Cubit.");
    while ($emp_income_sources_data = pg_fetch_array($rslt)) {
        if ($emp_income_sources_data["rf_ind"] == "N") {
            $gross_non_retirement_funding_income += $emp_income_sources_data["amount"];
        }
    }
    // Gross Remuneration
    $gross_remuneration = $gross_retirement_funding_income + $gross_non_retirement_funding_income;
    $gross_remuneration_out = array(array("<b>CODE</b>" => "3695", "<b>DESCRIPTION</b>" => "GROSS TAXABLE ANNUAL PAYMENTS", "<b>AMOUNT</b>" => (int) $gross_taxable_annual_payments), array("<b>CODE</b>" => "3696", "<b>DESCRIPTION</b>" => "GROSS NON-TAXABLE INCOME", "<b>AMOUNT</b>" => (int) $gross_non_taxable_income), array("<b>CODE</b>" => "3697", "<b>DESCRIPTION</b>" => "GROSS RETIREMENT FUNDING INCOME", "<b>AMOUNT</b>" => (int) $gross_retirement_funding_income), array("<b>CODE</b>" => "3698", "<b>DESCRIPTION</b>" => "GROSS NON-RETIREMENT FUNDING INCOME", "<b>AMOUNT</b>" => (int) $gross_non_retirement_funding_income), array("<b>CODE</b>" => "3699", "<b>DESCRIPTION</b>" => "GROSS REMUNERATION", "<b>AMOUNT</b>" => (int) $gross_remuneration));
    $gross_remuneration_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 410), "<b>AMOUNT</b>" => array("width" => 70));
    // Deductions ------------------------------------------------------------
    $deductions_out = array();
    $deduction_pension_total = 0;
    $deduction_provident_total = 0;
    $deduction_medicalaid_total = 0;
    $deduction_medical_total2 = 0;
    $deduction_retirementann_total = 0;
    $deduction_premiumpol_total = 0;
    db_conn("cubit");
    $sql = "SELECT * FROM emp_deductions WHERE empnum='{$empnum}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($ded_data = pg_fetch_array($rslt)) {
        $deductions_out[] = array("<b>CODE</b>" => "{$ded_data['code']}", "<b>DESCRIPTION</b>" => "{$ded_data['description']}", "<b>CLEARANCE NO</b>" => "{$ded_data['clearance_no']}", "<b>AMOUNT</b>" => (int) $ded_data["amount"]);
    }
    #handle pension deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Pension' AND type = 'DEDP' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_pension_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4001", "<b>DESCRIPTION</b>" => "Current pension fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_pension_total);
    #handle provident deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Provident' AND type = 'DEDV' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_provident_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4003", "<b>DESCRIPTION</b>" => "Current provident fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_provident_total);
    #handle medical DEDUCTIONS in income table ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Medical Contribution' AND type = 'DEDM' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee income sources from Cubit.");
    while ($empinc_data = pg_fetch_array($rslt)) {
        $deduction_medical_total2 += $empinc_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4005", "<b>DESCRIPTION</b>" => "Medical Contribution", "<b>RF IND</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_medical_total2);
    #handle retirement annuity deduction ...
    $sql = "SELECT amount FROM emp_ded WHERE emp='{$empnum}' AND description = 'Retirement Annuity Fund' AND type = 'DEDR' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_retirementann_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4006", "<b>DESCRIPTION</b>" => "Current retirement annuity fund contributions", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_retirementann_total);
    $sql = "SELECT * FROM emp_ded WHERE emp='{$empnum}' AND description!='UIF' AND description!='SDL' AND description!='PAYE' AND description!='Motorcar 1 Contribution for Use' AND description!='Motorcar 2 Contribution for Use' AND description!='Medical Contribution' AND description!='Pension' AND description!='Provident' AND description!='Retirement Annuity Fund' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    while ($empded_data = pg_fetch_array($rslt)) {
        $deduction_premiumpol_total += $empded_data['amount'];
    }
    $deductions_out[] = array("<b>CODE</b>" => "4018", "<b>DESCRIPTION</b>" => "Premiums paid on loss of income policies", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => (int) $deduction_premiumpol_total);
    //old all encapsulating search ... only first to description checks were orginal ...
    //	$sql = "SELECT * FROM emp_ded WHERE emp='$empnum' AND description!='UIF' AND description!='SDL' AND description!='Motorcar 1 Contribution for Use' AND description!='Motorcar 2 Contribution for Use' AND description!='Medical Contribution' AND description!='Pension' AND description!='Provident' AND description!='Retirement Annuity Fund'";
    //	$rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.");
    //	while ($empded_data = pg_fetch_array($rslt)) {
    //		if ($empded_data["type"] != "PAYE") {
    //			$deductions_out[] = array (
    //				"<b>CODE</b>"=>"$empded_data[code]",
    //				"<b>DESCRIPTION</b>"=>"$empded_data[description]",
    //				"<b>CLEARANCE NO</b>"=>"",
    //				"<b>AMOUNT</b>"=>(int)$empded_data["amount"]
    //			);
    //		}
    //	}
    // cant just remove whatever deductions is on system if they havent actually been applied to salary (ie. salary processed)
    // this value will come from same place as the rest of the income/deductions ... wth
    //	db_conn("cubit");
    //	$sql = "SELECT * FROM empdeduct WHERE empnum='$empnum'";
    //	$empded_rslt = db_exec($sql) or errDie("Unable to retrieve employee deductions from Cubit.'");
    //
    //	while ($empded_data = pg_fetch_array($empded_rslt)) {
    //		db_conn("cubit");
    //		$sql = "SELECT deduction, code FROM salded WHERE id='$empded_data[dedid]' AND deduction!='UIF'";
    //		$rslt = db_exec($sql) or errDie("Unable to retrieve deduction information from Cubit.");
    //		$ded_data = pg_fetch_array($rslt);
    //
    //		$deductions_out[] = array (
    //			"<b>CODE</b>"=>"$ded_data[code]",
    //			"<b>DESCRIPTION</b>"=>"$ded_data[deduction]",
    //			"<b>CLEARANCE NO</b>"=>"$empded_data[clearance_no]",
    //			"<b>AMOUNT</b>"=>(int)$empded_data["amount"], 2
    //		);
    //	}
    if (!isset($deductions_out[0])) {
        $deductions_out = array(array("<b>CODE</b>" => "", "<b>DESCRIPTION</b>" => "", "<b>CLEARANCE NO</b>" => "", "<b>AMOUNT</b>" => ""));
    }
    $deductions_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 340), "<b>CLEARANCE NO</b>" => array("width" => 70), "<b>AMOUNT</b>" => array("width" => 70));
    // Employees Tax deductions-----------------------------------------------
    $tax_amt = 0;
    // Retrieve PAYE amount from Cubit
    db_conn("cubit");
    $sql = "SELECT * FROM emp_ded WHERE type='PAYE' AND emp = '{$empnum}' AND year = '{$cyear}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve PAYE deductions from Cubit");
    $paye_amount = 0;
    while ($empded_data = pg_fetch_array($rslt)) {
        // add 375 to site if salary, -375 if reverse salary
        $tax_amt += 375 * ($empded_data["amount"] > 0 ? 1 : -1);
        $paye_amount += $empded_data["amount"];
    }
    if ($tax_amt > $paye_amount) {
        $tax_amt = $paye_amount;
        $paye_amount = 0;
    } else {
        $paye_amount -= $tax_amt;
    }
    $tax_deductions_amount = $paye_amount + $tax_amt;
    $employees_tax_deductions_out = array(array("<b>CODE</b>" => "4101", "<b>DESCRIPTION</b>" => "STANDARD INCOME TAX ON EMPLOYEES-SITE", "<b>AMOUNT</b>" => sprint($tax_amt, 2)), array("<b>CODE</b>" => "4102", "<b>DESCRIPTION</b>" => "PAY AS YOU EARN - PAYE", "<b>AMOUNT</b>" => sprint($paye_amount, 2)), array("<b>CODE</b>" => "4103", "<b>DESCRIPTION</b>" => "TOTAL EMPLOYEES TAX", "<b>AMOUNT</b>" => sprint($tax_deductions_amount, 2)));
    $employees_tax_deductions_cols = array("<b>CODE</b>" => array("width" => 40), "<b>DESCRIPTION</b>" => array("width" => 410), "<b>AMOUNT</b>" => array("width" => 70));
    // -----------------------------------------------------------------------
    // Do the actual rendering of the pdf
    // -----------------------------------------------------------------------
    $pdf =& new Cezpdf();
    global $set_mainFont;
    $pdf->selectFont($set_mainFont);
    $pdf->addInfo("Title", "IRP 5 for {$empinfo['fnames']} {$empinfo['sname']}");
    $pdf->addInfo("Author", USER_NAME);
    $irp5_pos = drawText(&$pdf, "<b>IRP 5</b>", 14, 520 - $pdf->getTextWidth(14, "<b>IRP 5</b>"), 0);
    $header_pos = drawText(&$pdf, $header_out, 12, 520 - $pdf->getTextWidth(12, $header_out), $irp5_pos['y'] + 14);
    // Employer information --------------------------------------------------
    $employer_information_head = drawText(&$pdf, "<b>EMPLOYER INFORMATION</b>", 8, 0, $irp5_pos['y'] + 14);
    $employer_trading_name_pos = drawTable2(&$pdf, $employer_trading_name_out, 0, $employer_information_head['y'] + 2, 520, 1);
    $employer_irp5_number_pos = drawTable2(&$pdf, $employer_irp5_number_out, 0, $employer_trading_name_pos['y'], 260, 1);
    $employer_reference_number_pos = drawTable2(&$pdf, $employer_reference_number_out, 0, $employer_irp5_number_pos['y'], 260, 1);
    $employer_tax_year_pos = drawTable2(&$pdf, $employer_tax_year_out, 0, $employer_reference_number_pos['y'], 260, 1);
    $employer_diplomatic_indemnity_pos = drawTable2(&$pdf, $employer_diplomatic_indemnity_out, 0, $employer_tax_year_pos['y'], 260, 1);
    $employer_business_address_pos = drawTable2(&$pdf, $employer_business_address_out, $employer_irp5_number_pos['x'] + 20, $employer_trading_name_pos['y'], 240, 4);
    $employer_postal_code_pos = drawTable2(&$pdf, $employer_postal_code_out, $employer_irp5_number_pos['x'] + 20, $employer_business_address_pos['y'], 240, 1, $employer_postal_code_cols);
    // Employee information --------------------------------------------------
    $employee_information_head = drawText(&$pdf, "<b>EMPLOYEE INFORMATION</b>", 8, 0, $employer_postal_code_pos['y'] + 15);
    $employee_nature_pos = drawTable2(&$pdf, $employee_nature_out, 0, $employee_information_head['y'], 100, 1);
    $employee_surname_pos = drawTable2(&$pdf, $employee_surname_out, $employee_nature_pos['x'] + 20, $employee_information_head['y'], 400, 1);
    $employee_first_names_pos = drawTable2(&$pdf, $employee_first_names_out, 0, $employee_nature_pos['y'], 400, 1);
    $employee_initials_pos = drawTable2(&$pdf, $employee_initials_out, $employee_first_names_pos['x'] + 20, $employee_nature_pos['y'], 100, 1);
    $employee_identity_number_pos = drawTable2(&$pdf, $employee_identity_number_out, 0, $employee_first_names_pos['y'], 260, 1);
    $employee_residential_pos = drawTable2(&$pdf, $employee_residential_out, $employee_identity_number_pos['x'] + 20, $employee_first_names_pos['y'], 240, 4);
    $employee_postal_code_pos = drawTable2(&$pdf, $employee_postal_code_out, $employee_identity_number_pos['x'] + 20, $employee_residential_pos['y'], 240, 1, $employee_postal_code_cols);
    $employee_number_pos = drawTable2(&$pdf, $employee_number_out, $employee_identity_number_pos['x'] + 20, $employee_postal_code_pos['y'], 240, 1);
    $employee_passport_number_pos = drawTable2(&$pdf, $employee_passport_number_out, 0, $employee_identity_number_pos['y'], 260, 1);
    $employee_date_of_birth_pos = drawTable2(&$pdf, $employee_date_of_birth_out, 0, $employee_passport_number_pos['y'], 260, 1);
    $employee_cc_number_pos = drawTable2(&$pdf, $employee_cc_number_out, 0, $employee_date_of_birth_pos['y'], 260, 1);
    $employee_tax_number_pos = drawTable2(&$pdf, $employee_tax_number_out, 0, $employee_cc_number_pos['y'], 260, 1);
    // Tax calculation information -------------------------------------------
    $tax_calculation_head = drawText(&$pdf, "<b>TAX CALCULATION INFORMATION</b>", 8, 0, $employee_number_pos['y'] + 15);
    $tax_prd_employed_frm_pos = drawTable2(&$pdf, $tax_prd_employed_frm_out, 0, $tax_calculation_head['y'], 160, 1);
    $tax_prd_employed_to_pos = drawTable2(&$pdf, $tax_prd_employed_to_out, $tax_prd_employed_frm_pos['x'] + 20, $tax_calculation_head['y'], 160, 1);
    $tax_over_deduction_pos = drawTable2(&$pdf, $tax_over_deduction_out, $tax_prd_employed_to_pos['x'] + 20, $tax_calculation_head['y'], 160, 1);
    $tax_prd_in_year_pos = drawTable2(&$pdf, $tax_prd_in_year_out, 0, $tax_prd_employed_frm_pos['y'], 115, 1);
    $tax_prd_worked_pos = drawTable2(&$pdf, $tax_prd_worked_out, $tax_prd_in_year_pos['x'] + 20, $tax_prd_employed_frm_pos['y'], 115, 1);
    $tax_fixed_rate_income_pos = drawTable2(&$pdf, $tax_fixed_rate_income_out, $tax_prd_worked_pos['x'] + 20, $tax_prd_employed_frm_pos['y'], 115, 1);
    $tax_directive_number_pos = drawTable2(&$pdf, $tax_directive_number_out, $tax_fixed_rate_income_pos['x'] + 20, $tax_prd_employed_frm_pos['y'], 115, 1);
    // Income sources --------------------------------------------------------
    $income_sources_head = drawText(&$pdf, "<b>INCOME SOURCE</b>", 8, 0, $tax_prd_in_year_pos['y'] + 15);
    $income_sources_pos = drawTable2(&$pdf, $income_sources_out, 0, $income_sources_head['y'] + 2, 520, 20, $income_sources_cols, 1);
    $gross_remuneration_head = drawText(&$pdf, "<b>GROSS REMUNERATION</b>", 8, 0, $income_sources_pos['y'] + 15);
    $gross_remuneration_pos = drawTable2(&$pdf, $gross_remuneration_out, 0, $gross_remuneration_head['y'] + 2, 520, 5, $gross_remuneration_cols, 1);
    $deductions_head = drawText(&$pdf, "<b>DEDUCTIONS</b>", 8, 0, $gross_remuneration_pos['y'] + 15);
    $deductions_pos = drawTable2(&$pdf, $deductions_out, 0, $deductions_head['y'] + 2, 520, 15, $deductions_cols, 1);
    $employees_tax_deductions_head = drawText(&$pdf, "<b>EMPLOYEES TAX DEDUCTIONS</b>", 8, 0, $deductions_pos['y'] + 15);
    $employees_tax_deductions_pos = drawTable2(&$pdf, $employees_tax_deductions_out, 0, $employees_tax_deductions_head['y'] + 2, 520, 3, $employees_tax_deductions_cols, 1);
    // Footer note -----------------------------------------------------------
    $certificate_attatch = drawText(&$pdf, "Attach this certificate to your income tax return or retain it. / ", 6, 0, $employees_tax_deductions_pos['y'] + 10);
    $pdf->ezStream();
}
function printPurch($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purnum, "num", 1, 10, "Invalid Purchase number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return slct($purnum, $confirm);
    }
    db_connect();
    # local
    $sql = "SELECT * FROM purchases WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($purRslt) > 0) {
        $pur = pg_fetch_array($purRslt);
        if ($pur['supid'] != 0) {
            $recv = "purch-recv.php?purid={$pur['purid']}";
        } else {
            $recv = "purch-recv-cash.php?purid={$pur['purid']}";
        }
        header("Location: {$recv}");
    }
    # inter
    $sql = "SELECT * FROM purch_int WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($purRslt) > 0) {
        $pur = pg_fetch_array($purRslt);
        $recv = "purch-int-recv.php?purid={$pur['purid']}";
        header("Location: {$recv}");
    }
    # nons
    $sql = "SELECT * FROM nons_purchases WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($purRslt) > 0) {
        $pur = pg_fetch_array($purRslt);
        $recv = "nons-purch-recv.php?purid={$pur['purid']}";
        header("Location: {$recv}");
    }
    # inter nons
    $sql = "SELECT * FROM nons_purch_int WHERE purnum = '{$purnum}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($purRslt) > 0) {
        $pur = pg_fetch_array($purRslt);
        $recv = "nons-purch-int-recv.php?purid={$pur['purid']}";
        header("Location: {$recv}");
    }
    return slct($purnum, "<li class=err> - Purchase number not found in outstanding purchases.");
}
            if (!isset($_POST["done"])) {
                $OUTPUT = slct($_POST);
            } else {
                $OUTPUT = printCenter($_POST);
            }
            break;
        case "export":
            $OUTPUT = export_data($_POST);
            break;
        default:
            $OUTPUT = slct($_POST);
            break;
    }
} else {
    # Display default output
    $OUTPUT = slct($_POST);
}
$OUTPUT .= "\n\t<br>\n\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='costcenter-view.php'>View Cost Center</a></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t</tr>\n\t</table>";
require "template.php";
# Default view
function slct($_POST)
{
    extract($_POST);
    if (!isset($prd)) {
        $prd = "";
    }
    if (!isset($project1)) {
        $project1 = "";
    }
    if (!isset($project2)) {
        $project2 = "";
function printtemp($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invnum, "num", 1, 10, "Invalid invoice num.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm . slct();
    }
    # Set up table to display in
    $printInv = "\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Temp Num</th>\n\t\t\t\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $sql = "SELECT * FROM ncsrec WHERE newnum = '{$invnum}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li> No Outstanding Invoices found.";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $printInv .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$inv['oldnum']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['newnum']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t";
            $i++;
        }
    }
    $printInv .= "\n\t\t\t\t\t</table>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t<td><a href='main.php'>Main Menu</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t";
    return $printInv;
}
function report($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    //$v->isOk ($stkid, "num", 1, 50, "Invalid stock number.");
    $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.");
    $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.");
    }
    if (!isset($stkids)) {
        $v->addError("", "Please select at least on stock item.");
    }
    if ($v->isError()) {
        return slct($v->genErrors());
    }
    $freport = "";
    if (in_array('all', $stkids)) {
        $stkids = $alls;
    }
    $ss = "";
    foreach ($stkids as $stkid) {
        $ss .= "<input type='hidden' name='stkids[]' value='{$stkid}'>";
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID.</li>";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        db_connect();
        $sql = "SELECT * FROM stockrec WHERE edate >= '{$fromdate}' AND edate <= '{$todate}' AND stkid = '{$stkid}' AND (trantype = 'invoice' OR trantype='note') ORDER BY edate DESC";
        $recRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        $records = "";
        $totprof = 0;
        $totprice = 0;
        $totqty = 0;
        while ($rec = pg_fetch_array($recRslt)) {
            $rec['edate'] = explode("-", $rec['edate']);
            $rec['edate'] = $rec['edate'][2] . "-" . $rec['edate'][1] . "-" . $rec['edate'][0];
            if ($rec['trantype'] == "note") {
                $rec['qty'] = -$rec['qty'];
                $rec['csprice'] = -$rec['csprice'];
                $rec['csamt'] = -$rec['csamt'];
            }
            $totqty += $rec['qty'];
            $prof = $rec['csprice'] - $rec['csamt'];
            $totprof += $prof;
            $totprice += $rec['csprice'];
            $records .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$rec['edate']}</td>\n\t\t\t\t<td>{$rec['details']}</td>\n\t\t\t\t<td>" . sprint3($rec['qty']) . "</td>\n\t\t\t\t<td>" . CUR . sprint($rec["csprice"]) . "</td>\n\t\t\t\t<td>" . CUR . sprint($prof) . "</td>\n\t\t\t</tr>";
        }
        $totprice = sprint($totprice);
        $totprof = sprint($totprof);
        $totqty = sprint3($totqty);
        $freport .= "\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'>Details</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Warehouse</td>\n\t\t\t\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Stock code</td>\n\t\t\t\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Stock description</td>\n\t\t\t\t\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Category</td>\n\t\t\t\t\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Category</td>\n\t\t\t\t\t\t\t\t<td>{$stk['classname']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t\t<th>Details</th>\n\t\t\t\t\t\t\t\t<th>Quantity</th>\n\t\t\t\t\t\t\t\t<th>Selling Price</th>\n\t\t\t\t\t\t\t\t<th>Gross Profit</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t{$records}\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Totals</b></td>\n\t\t\t\t\t\t\t\t<td>{$totqty}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$totprice}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$totprof}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t" . TBL_BR;
    }
    $report = "\n\t\t\t\t<h3>Stock Sales Report</h3>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t{$freport}\n\t\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t\t\t{$ss}\n\t\t\t\t\t<input type='hidden' name='fday' value='{$from_day}'>\n\t\t\t\t\t<input type='hidden' name='fmon' value='{$from_month}'>\n\t\t\t\t\t<input type='hidden' name='fyear' value='{$from_year}'>\n\t\t\t\t\t<input type='hidden' name='today' value='{$to_day}'>\n\t\t\t\t\t<input type='hidden' name='tomon' value='{$to_month}'>\n\t\t\t\t\t<input type='hidden' name='toyear' value='{$to_year}'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>" . mkQuickLinks(ql("stock-sales-rep.php", "Sales Report"));
    return $report;
}
function printInv()
{
    extract($_REQUEST);
    if (isset($button)) {
        list($button) = array_keys($button);
    }
    # 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;
    }
    # Set up table to display in
    $printInv = "\n\t\t<form method='post' action='" . SELF . "'>\n\t\t\t<input type='hidden' name='key' value='view' />\n\t\t\t<input type='hidden' name='from_year' value='{$from_year}' />\n\t\t\t<input type='hidden' name='from_month' value='{$from_month}' />\n\t\t\t<input type='hidden' name='from_day' value='{$from_day}' />\n\t\t\t<input type='hidden' name='to_year' value='{$to_year}' />\n\t\t\t<input type='hidden' name='to_month' value='{$to_month}' />\n\t\t\t<input type='hidden' name='to_day' value='{$to_day}' />\n\t\t<h3>View Cash Point of Sale 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>Sales Person</th>\n\t\t\t\t<th>Inv No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th colspan='4'>Options</th>\n\t\t\t\t<th>&nbsp;</th>\t\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $sql = "SELECT invid, total, odate, deptname, salespn, cusname, printed, balance,cusnum FROM pinvoices WHERE odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>No Point of Sale Invoices found for the selected date range.</li>" . slct();
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $tot1 = $tot1 + $inv['total'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['cusnum'] != "0") {
                #overwrite the default cusname
                $get_cust = "SELECT surname FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
                $run_cust = db_exec($get_cust) or errDie("Unable to get customer information.");
                if (pg_numrows($run_cust) == 1) {
                    $arr = pg_fetch_array($run_cust);
                    $inv['cusname'] = $arr['surname'];
                }
            }
            $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>TP {$inv['invid']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']}</td>\n\t\t\t\t\t<td align=right>" . CUR . " {$inv['total']}</td>\n\t\t\t\t\t<td><a href='pos-invoice-details.php?invid={$inv['invid']}'>Details</a></td>";
            if ($inv['printed'] == "n") {
                $printInv .= "\n\t\t\t\t\t<td><a href='pos-invoice-new.php?invid={$inv['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?invid={$inv['invid']}&key=delete_confirm'>Delete</a></td>\n\t\t\t\t\t<td><a target='_blank' href='pos-invoice-print.php?invid={$inv['invid']}'>Process</a></td>";
            } else {
                $printInv .= "\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<a target='_blank' href='pos-invoice-reprint.php?invid={$inv['invid']}'>Reprint</a>\n\t\t\t\t\t</td>";
            }
            if (isset($button) && $button == "allsel") {
                $checked = "checked='checked'";
            } else {
                $checked = "";
            }
            $printInv .= "\n\t\t\t\t\t<td><input type='checkbox' name='rem[{$inv['invid']}]' value='{$inv['invid']}' {$checked} /></td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    // Layout
    $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='5'>Total Invoices: {$i}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$tot1}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='15' align='right'>\n\t\t\t\t\t\t<input type='submit' name='button[cancelsel]' value='Cancel Selected' />\n\t\t\t\t\t\t<input type='submit' name='button[allsel]' value='Select All' />\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr><td><br></td></tr>\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='pos-invoice-new.php'>New Point of Sale Invoice</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='pos-invoice-list.php'>View Unprocessed Point of Sale Invoice</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $printInv;
}
function printSerial($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($serno, "string", 1, 10, "Invalid Serial number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($serno, $confirm);
    }
    $serlist = "";
    $details = "no details";
    db_connect();
    $sql = "SELECT * FROM serialrec WHERE serno LIKE '%{$serno}%' AND div = '" . USER_DIV . "' ORDER BY recid ASC";
    $serRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($serRslt) > 0) {
        while ($ser = pg_fetch_array($serRslt)) {
            $stk = qryStock($ser["stkid"]);
            switch ($ser['typ']) {
                case "inv":
                    $details = "Invoiced to {$ser['cusname']} Invoice No. {$ser['invnum']}";
                    break;
                case "note":
                    $details = "Received from {$ser['cusname']} Credit Note No. {$ser['invnum']}";
                    break;
                case "pur":
                    $details = "Purchased from Supplier {$ser['cusname']} Purchase No. {$ser['invnum']}";
                    break;
                case "ret":
                    $details = "Returned to Supplier {$ser['cusname']} Purchase No. {$ser['invnum']}";
                    break;
                case "tran":
                    $details = "Stock Decrease Transaction : {$ser['cusname']}";
                    break;
            }
            $ser['edate'] = ext_rdate($ser['edate']);
            $serlist .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$ser['serno']}</td>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td>{$details}</td>\n\t\t\t\t\t<td align='center'>&nbsp;&nbsp;&nbsp;{$ser['tdate']}&nbsp;&nbsp;&nbsp;</td>\n\t\t\t\t\t<td>{$stk['warranty']}</td>\n\t\t\t\t</tr>";
        }
    } elseif (ext_findSer($serno)) {
        $sers = ext_findSer($serno);
        foreach ($sers as $key => $ser) {
            # Get selected stock
            db_connect();
            $sql = "SELECT stkdes,stkcod FROM stock WHERE stkid = '{$ser['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $serlist .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$ser['serno']}</td>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td align='center'>Available</td>\n\t\t\t\t\t<td align='center'>---</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
        }
    } else {
        $err = "<li class='err'>Serial Number <b>{$serno}</b> not found.</li>";
        return slct($serno, $err);
    }
    $serials = "\n\t\t<center>\n\t\t<h3>Stock Serial Numbers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Serial No.</th>\n\t\t\t\t<th>Stock Code</th>\n\t\t\t\t<th>Stock Description</th>\n\t\t\t\t<th>Details</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Warranty</th>\n\t\t\t</tr>\n\t\t\t{$serlist}\n\t\t\t<tr><td><br></td></tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\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='" . SELF . "'>Find Another</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $serials;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Purchase number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($supid, "num", 1, 20, "Invalid supplier account number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slct($_POST, $error);
        $confirm = "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li class='err'>purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($p_year, $p_month, $p_day) = explode("-", $pur['pdate']);
    $supacc = "<select name='supacc'>";
    core_connect();
    $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY accname ASC";
    $accRslt = db_exec($sql);
    if (pg_numrows($accRslt) < 1) {
        return "<li>There are No accounts in Cubit.</li>";
    }
    while ($acc = pg_fetch_array($accRslt)) {
        # Check Disable
        if (isDisabled($acc['accid'])) {
            continue;
        }
        $supacc .= "<option value='{$acc['accid']}'>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</option>";
    }
    $supacc .= "</select>";
    # Get selected supplier info
    db_connect();
    $hide = "";
    if (isset($ctyp) && $ctyp == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            $supacc = $sup['supno'];
            $hide = "<input type='hidden' name='supid' value='{$supid}'><input type='hidden' name='ctyp' value='{$ctyp}'>";
        }
    } elseif (isset($ctyp) && $ctyp == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = "{$dept['deptname']} - Cash on Hand";
            $hide = "<input type='hidden' name='deptid' value='{$deptid}'><input type='hidden' name='ctyp' value='{$ctyp}'>";
        }
    } elseif (isset($ctyp) && $ctyp == 'p') {
        core_connect();
        # Get Petty cash account
        $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
        # Get account name for thy lame User's Sake
        $accRslt = get("core", "*", "accounts", "accid", $cashacc);
        if (pg_numrows($accRslt) < 1) {
            return "<li class='err'> Petty Cash Account not found.</li>";
        }
        $acc = pg_fetch_array($accRslt);
        $supacc = "{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}";
        $hide = "<input type='hidden' name='supacc' value='{$cashacc}'><input type='hidden' name='ctyp' value='{$ctyp}'>";
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY RECEIVED</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT *, (qty - rqty) as qty FROM nons_pur_items  WHERE purid = '{$purid}' AND (qty - rqty) > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='hidden' size='4' name='cod[]' value='{$stkd['cod']}'>{$stkd['cod']}</td>\n\t\t\t\t<td>{$stkd['des']}</td>\n\t\t\t\t<td><input type='hidden' name='qts[]' value='{$stkd['qty']}'><input type='text' size='5' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td nowrap><input type='hidden' size='4' name='unitcost[]' value='{$stkd['unitcost']}'>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t<td>{$sday}-{$smon}-{$syear}</td>\n\t\t\t\t<td nowrap>" . CUR . " {$stkd['amt']}</td>\n\t\t\t</tr>";
        $key++;
    }
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h3>Non-Stock Purchase received</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t<input type='hidden' name='key' value='update'>\n\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t<input type='hidden' name='shipchrg' value='0'>\n\t\t{$hide}\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['supplier']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Supplier Address</td>\n\t\t\t\t\t\t\t<td valign='center'><pre>{$pur['supaddr']}</pre></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Select the account you wish to Credit") . ">\n\t\t\t\t\t\t\t<td>Account</td>\n\t\t\t\t\t\t\t<td>{$supacc}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Purchase Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Non-Stock Purchase No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Ref No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' name='refno' size='10' value='{$pur['refno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['terms']} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("p", $p_year, $p_month, $p_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['vatinc']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purchase-new.php'>New purchase</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT @ " . TAX_VAT . " %</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$pur['vat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' name='upBtn' value='Write'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t</center>";
    return $details;
}
function printStk()
{
    extract($_POST);
    if (!isset($sortby)) {
        $sortby = "normal";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($whid, "num", 1, 50, "Invalid Warehouse.");
    $v->isOk($fld, "string", 1, 50, "Invalid Search Field.");
    $v->isOk($skey, "string", 0, 50, "Invalid Search Key.");
    $v->isOk($sortby, "string", 1, 10, "Invalid Sort Selection.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    if (!isset($sortby)) {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "";
    } elseif ($sortby == "cat") {
        $sel1 = "";
        $sel2 = "checked='yes'";
        $sel3 = "";
    } elseif ($sortby == "class") {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "checked='yes'";
    } else {
        $sel1 = "checked='yes'";
        $sel2 = "";
        $sel3 = "";
    }
    if ($key == "export") {
        $pure = true;
    } else {
        $pure = false;
    }
    # Set up table to display in
    $OUT = "";
    if (!$pure) {
        $OUT .= "\n\t\t\t<h3>View Stock</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t\t<input type='hidden' name='fld' value='{$fld}'>\n\t\t\t\t<input type='hidden' name='skey' value='{$skey}'>\n\t\t\t\t<input type='hidden' name='whid' value='{$whid}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Sort By:</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='radio' name='sortby' {$sel1} value='normal' onChange='javascript:document.form1.submit();'> Normal\n\t\t\t\t\t\t<input type='radio' name='sortby' {$sel2} value='cat' onChange='javascript:document.form1.submit();'> Category\n\t\t\t\t\t\t<input type='radio' name='sortby' {$sel3} value='class' onChange='javascript:document.form1.submit();'> Classification\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t</table>";
    }
    $OUT .= "<table " . TMPL_tblDflts . ">";
    #search parms
    if ($sortby == "cat") {
        $Ord = "catname,stkcod";
    } elseif ($sortby == "class") {
        $Ord = "classname,stkcod";
    } else {
        $Ord = "stkcod";
    }
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    switch ($fld) {
        default:
            $sql = "\n\t\t\t\tSELECT * FROM stock \n\t\t\t\tWHERE whid = '{$whid}' AND lower({$fld}) ILIKE '%{$skey}%' AND div = '" . USER_DIV . "' \n\t\t\t\tORDER BY {$Ord} ASC";
            break;
        case "supstkcod":
            $sql = "\n\t\t\t\tSELECT DISTINCT stock.stkid FROM cubit.suppstock \n\t\t\t\t\tLEFT JOIN cubit.stock ON suppstock.stkid=stock.stkid \n\t\t\t\tWHERE suppstock.stkcod ILIKE '{$skey}%'";
            $supcod_rslt = db_exec($sql) or errDie("Unable to retrieve supplier stock codes.");
            $stkids = array();
            while ($supcod_data = pg_fetch_array($supcod_rslt)) {
                $stkids[] = "stkid='{$supcod_data['stkid']}'";
            }
            $stkids = implode(" OR ", $stkids);
            if (!empty($stkids)) {
                $stkids = "AND ({$stkids})";
            } else {
                $stkids = "AND stkid='-12345'";
            }
            $sql = "SELECT * FROM cubit.stock WHERE whid='{$whid}' AND div='" . USER_DIV . "' {$stkids} ORDER BY {$Ord} ASC";
            break;
    }
    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    if (pg_numrows($stkRslt) < 1) {
        $confirm = "<li class='err'>No Stock Found.</li>";
        return slct($confirm);
    }
    $tc = 0;
    $tu = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $heading = "";
    $showheading = "";
    while ($stk = pg_fetch_array($stkRslt)) {
        $stk['csamt'] = sprint($stk['csamt']);
        if ($sortby == "cat") {
            if ($stk['catname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['catname']}</b></font></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t<th>Cost of all goods on hand</th>\n\t\t\t\t\t\t<th>Cost per Unit</th>\n\t\t\t\t\t\t<th>Selling Price</th>\n\t\t\t\t\t\t<th>Last Cost Price</th>\n\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t<th>On Order</th>\n\t\t\t\t\t\t<th>Min Lev</th>\n\t\t\t\t\t\t<th>Max Lev</th>\n\t\t\t\t\t\t<th>Measure Unit</th>\n\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='8'>Options</th>") . "\n\t\t\t\t\t</tr>";
            }
        } elseif ($sortby == "class") {
            if ($stk['classname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['classname']}</b></font></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t<th>Cost of all goods on hand</th>\n\t\t\t\t\t\t<th>Cost per Unit</th>\n\t\t\t\t\t\t<th>Selling Price</th>\n\t\t\t\t\t\t<th>Last Cost Price</th>\n\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t<th>On Order</th>\n\t\t\t\t\t\t<th>Min Lev</th>\n\t\t\t\t\t\t<th>Max Lev</th>\n\t\t\t\t\t\t<th>Measure Unit</th>\n\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='8'>Options</th>") . "\n\t\t\t\t\t</tr>";
            }
        } else {
            if ($heading == "normal") {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t<th>Cost of all goods on hand</th>\n\t\t\t\t\t\t<th>Cost per Unit</th>\n\t\t\t\t\t\t<th>Selling Price</th>\n\t\t\t\t\t\t<th>Last Cost Price</th>\n\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t<th>On Order</th>\n\t\t\t\t\t\t<th>Min Lev</th>\n\t\t\t\t\t\t<th>Max Lev</th>\n\t\t\t\t\t\t<th>Measure Unit</th>\n\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='8'>Options</th>") . "\n\t\t\t\t\t</tr>";
            }
        }
        $OUT .= $showheading;
        $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t<td>{$stk['classname']}</td>\n\t\t\t\t<td align='right'>" . sprint3($stk['units']) . "</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($stk['csamt']) . "</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($stk["csprice"]) . "</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($stk["selamt"]) . "</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($stk["lcsprice"]) . "</td>\n\t\t\t\t<td align='right'>" . sprint3($stk['alloc']) . "</td>\n\t\t\t\t<td align='right'>" . sprint3($stk['ordered']) . "</td>\n\t\t\t\t<td align='right'>{$stk['minlvl']}</td>\n\t\t\t\t<td align='right'>{$stk['maxlvl']}</td>\n\t\t\t\t<td>{$stk['suom']}</td>";
        if (!$pure) {
            $OUT .= "\n\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>View Report</a></td>\n\t\t\t\t<td><a href='stock-det.php?stkid={$stk['stkid']}'>Details</a></td>\n\t\t\t\t<td><a href='stock-edit.php?stkid={$stk['stkid']}'>Edit</a></td>\n\t\t\t\t<td><a href='stock-balance.php?stkid={$stk['stkid']}'>Transaction</a></td>";
            if ($stk['blocked'] == 'y') {
                $OUT .= "<td><a href='stock-unblock.php?stkid={$stk['stkid']}'>Unblock</a></td>";
            } else {
                $OUT .= "<td><a href='stock-block.php?stkid={$stk['stkid']}'>Block</a></td>";
            }
            if ($stk['units'] < 1 && $stk['alloc'] < 1) {
                $OUT .= "<td><a href='stock-rem.php?stkid={$stk['stkid']}'>Remove</a></td>";
            } elseif ($stk['alloc'] > 0) {
                $OUT .= "<td><a href='#' onclick='openwindow(\"stock-alloc.php?stkid={$stk['stkid']}\")'>View Allocation</a></td></tr>";
            } else {
                $OUT .= "<td></td></tr>";
            }
        }
        if ($sortby == "cat") {
            $heading = $stk['catname'];
        } elseif ($sortby == "class") {
            $heading = $stk['classname'];
        } else {
            $heading = "normal";
        }
        $tc += $stk['csamt'];
        $tu += $stk['units'];
        $tot1 += $stk['csamt'];
        $tot2 += $stk['csprice'];
        $tot3 += $stk['selamt'];
        $tot4 += $stk['lcsprice'];
    }
    $t = sprint($tc);
    $OUT .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='4'>Totals</td>\n\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($tot1) . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($tot2) . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($tot3) . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " " . sprint($tot4) . "</td>\n\t\t</tr>";
    if (!$pure) {
        $OUT .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t\t<input type='hidden' name='whid' value='{$whid}'>\n\t\t\t\t<input type='hidden' name='fld' value='{$fld}'>\n\t\t\t\t<input type='hidden' name='skey' value='{$skey}'>\n\t\t\t\t<input type='hidden' name='sortby' value='{$sortby}'>\n\t\t\t\t<tr><td><input type='submit' value='Export to Spreadsheet'></td></tr>\n\t\t\t</form>\n\t\t\t</table>" . mkQuickLinks(ql("stock-add.php", "Add New Stock Item"));
    }
    return $OUT;
}