function update($_POST)
{
    # Get Vars ( banked[] )
    extract($_POST);
    # check if anything is selected
    if (!isset($banked)) {
        $err = "<li class='err'> Please Select at least one entry to update.";
        return cashbook($_POST, $err);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $refnum = getrefnum();
    /*refnum*/
    db_conn('core');
    $rid = pglib_lastid("save_bank_recon", "id");
    $rid++;
    # Record all trans
    foreach ($banked as $key => $cashid) {
        # Connect to database
        db_Connect();
        $sql = "SELECT * FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve details from database.", SELF);
        $cash = pg_fetch_array($cashRslt);
        # Set record as banked
        db_connect();
        $sql = "UPDATE cashbook SET banked = 'yes',rid='{$rid}' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to set bank deposit as banked in Cubit.", SELF);
    }
    // Connect to database
    db_connect();
    $sql = "SELECT * FROM cashbook WHERE bankid = '{$bankid}' AND banked = 'no' AND div = '" . USER_DIV . "' ORDER BY date DESC";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank transactions from database.", SELF);
    $sql = "SELECT * FROM bankacct WHERE bankid= '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    $cur = CUR;
    $amtd = "amount";
    if ($bank['btype'] == 'int') {
        $currs = getSymbol($bank['fcid']);
        $cur = $currs['symbol'];
        $amtd = "famount";
    }
    $tot = 0;
    $totr = 0;
    $totp = 0;
    $recpts = "";
    $paymnts = "";
    while ($cash = pg_fetch_array($cashRslt)) {
        if ($cash['trantype'] == "deposit") {
            $recpts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totr += $cash[$amtd];
        } else {
            $paymnts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totp += $cash[$amtd];
        }
        $tot += $cash[$amtd];
    }
    $reconbal = sprint($cbal + ($totr - $totp));
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $banklnk = pg_fetch_array($rslt);
    # Get bank balance
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE period='12' AND accid = '{$banklnk['accnum']}' AND div = '" . USER_DIV . "'";
    $brslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    $bal = pg_fetch_array($brslt);
    if ($bank['btype'] == 'int') {
        $bal['bal'] = $bank['fbalance'];
    }
    $diff = sprint($reconbal - $bal['bal']);
    $derr = "";
    if ($diff != 0) {
        $derr = "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b class='err'>Bank statement and computer balance not balancing by</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>";
    }
    $totp = sprint($totp);
    // Layout
    $update = "\n\t\t<center>\n\t\t<h3>Bank Reconciliation Output</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='save'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width='80%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width=100%>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Bank Account : </b>{$bank['accname']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td align='right'><b>Prepared By : </b>" . USER_NAME . "</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><b>Closing Balance As per Bank Statement : </b>{$cur} {$cbal}</td>\n\t\t\t\t\t\t\t<td></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><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Plus Outstanding Receipts :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$recpts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totr}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Less Outstanding Payments :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$paymnts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totp}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><td></tr>\n\t\t\t{$derr}\n\t\t\t<tr><td><br><td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Reconciled Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$reconbal}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Computer Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$bal['bal']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Diff</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>";
    $upcode = base64_encode($update);
    $button = "</table></form>";
    core_connect();
    $gendate = date("Y-m-d");
    $sql = "\n\t\tINSERT INTO save_bank_recon (\n\t\t\tbankid, gendate, recon, div\n\t\t) VALUES (\n\t\t\t'{$bankid}', '{$gendate}', '{$upcode}', '" . USER_DIV . "'\n\t\t)";
    $saveRslt = db_exec($sql) or errDie("Unable to save bank recon to database", SELF);
    $update .= $button;
    $OUTPUT = $update;
    require "../tmpl-print.php";
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid purchase number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoices information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $currs = getSymbol($inv['fcid']);
    /* --- Start Products Display --- */
    # Products layout
    $products = "\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=100%>\n\t<tr>\n\t\t<th width='5%'>#</th>\n\t\t<th width='65%'>DESCRIPTION</th>\n\t\t<th width='10%'>QTY</th>\n\t\t<th width='10%' colspan=2>UNIT PRICE</th>\n\t\t<th width='10%'>AMOUNT</th>\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)) {
        $i++;
        # put in product
        $products .= "<tr class='bg-odd'>\n\t\t\t<td align=center>{$i}</td>\n\t\t\t<td>{$stkd['description']}</td>\n\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t<td>" . CUR . " {$stkd['cunitcost']}</td>\n\t\t\t<td>{$inv['currency']} {$stkd['unitcost']}</td>\n\t\t\t<td>{$inv['currency']} {$stkd['amt']}</td>\n\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['sdate']);
    if ($inv['invnum'] == 0) {
        $inv['invnum'] = $inv['invid'];
    }
    /* -- Final Layout -- */
    $details = "<center><h3>Non-Stock Invoice Details</h3>\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> Customer Details </th></tr>\n\t\t\t<tr class='bg-odd'><td>Customer</td><td valign=center>{$inv['cusname']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Customer Address</td><td valign=center><pre>{$inv['cusaddr']}</pre></td></tr>\n\t\t\t<tr class='bg-odd'><td>Customer Vat Number</td><td valign=center>{$inv['cusvatno']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Customer Order number</td><td valign=center>{$inv['cordno']}</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 Invoice Details </th></tr>\n\t\t\t<tr class='bg-odd'><td>Non-Stock Invoice No.</td><td valign=center>{$inv['invnum']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Proforma Inv No.</td><td valign=center>{$inv['docref']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Date</td><td valign=center>{$sday}-{$smon}-{$syear}</td></tr>\n\t\t\t<tr class='bg-even'><td>Foreign Currency</td><td valign=center>{$currs['symbol']} - {$currs['name']} &nbsp;&nbsp;Exchange rate " . CUR . " {$inv['xrate']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>VAT Inclusive</td><td valign=center>{$inv['chrgvat']}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td colspan=2>\n\t{$products}\n\t</td></tr>\n\t<tr><td>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\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>\n\t\t\t<tr><td class='bg-odd'><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>\n\t\t\t<tr class='bg-odd'><td><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\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>{$inv['currency']} {$inv['subtot']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>VAT @ " . TAX_VAT . " %</td><td align=right>{$inv['currency']} {$inv['vat']}</td></tr>\n\t\t\t<tr class='bg-even'><th>GRAND TOTAL</th><td align=right>{$inv['currency']} {$inv['total']}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t</table></form>\n\t</center>";
    return $details;
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # 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 "<i class=err>Not Found</i>";
    }
    $pur = pg_fetch_array($purRslt);
    # Currency
    $currs = getSymbol($pur['fcid']);
    $curr = $currs['symbol'];
    $currsel = "{$currs['symbol']} - {$currs['descrip']}";
    /* --- Start Products Display --- */
    # Products layout
    $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</th><th colspan=2>UNIT PRICE</th><th colspan=2>DUTY</th><th>LINE TOTAL</th><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);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # put in product
        $products .= "<tr class='bg-odd'><td>{$stkd['cod']}</td><td>{$stkd['des']}</td><td>{$stkd['qty']}</td><td>{$pur['curr']} {$stkd['cunitcost']} or </td><td>" . CUR . " {$stkd['unitcost']}</td><td>{$pur['curr']} {$stkd['duty']} or </td><td>{$stkd['dutyp']}%</td><td>{$pur['curr']} {$stkd['amt']}</td></tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get tax
    $tax = sprint($pur['tax']);
    /* --- End Some calculations --- */
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    list($dyear, $dmon, $dday) = explode("-", $pur['ddate']);
    /* -- Final Layout -- */
    $details = "<center><h3>International Non-Stock Order Details</h3>\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</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-odd'><td>Non-Stock Order No.</td><td valign=center>{$pur['purnum']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Order No.</td><td valign=center>{$pur['ordernum']}</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>{$pday}-{$pmon}-{$pyear}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Foreign Currency</td><td valign=center>{$currsel} &nbsp;&nbsp;Exchange rate {$pur['curr']} {$pur['xrate']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Tax</td><td valign=center>{$pur['curr']} {$pur['tax']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Shipping Charges</td><td valign=center>{$pur['curr']} {$pur['shipchrg']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Date</td><td valign=center>{$dday}-{$dmon}-{$dyear}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td colspan=2>\n\t{$products}\n\t</td></tr>\n\t<tr><td>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\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>\n\t\t\t<tr><td class='bg-odd'><a href='nons-purch-int-new.php'>New International Non-Stock Order</a></td><td class='bg-odd' rowspan=4 align=center valign=top>" . nl2br($pur['remarks']) . "</td></tr>\n\t\t\t<tr class='bg-odd'><td><a href='nons-purch-int-view.php'>View International Non-Stock Orders</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\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>{$pur['curr']} {$pur['subtot']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Charges</td><td align=right>{$pur['curr']} {$pur['shipping']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Tax </td><td align=right>{$pur['curr']} {$pur['tax']}</td></tr>\n\t\t\t<tr class='bg-even'><th>GRAND TOTAL</th><td align=right>{$pur['curr']} {$pur['total']}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t</table></form>\n\t</center>";
    return $details;
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # 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 "<i class='err'>Not Found</i>";
    }
    $pur = pg_fetch_array($purRslt);
    # Currency
    $currs = getSymbol($pur['fcid']);
    $curr = $currs['symbol'];
    $currsel = "{$currs['symbol']} - {$currs['descrip']}";
    /* --- Start Products Display --- */
    # Products layout
    $products = "\r\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' width='100%'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\r\n\t\t\t\t\t\t\t<th>DESCRIPTION</th>\r\n\t\t\t\t\t\t\t<th>QTY</th>\r\n\t\t\t\t\t\t\t<th colspan='2'>UNIT PRICE</th>\r\n\t\t\t\t\t\t\t<th colspan='2'>DUTY</th>\r\n\t\t\t\t\t\t\t<th>LINE TOTAL</th>\r\n\t\t\t\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);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # put in product
        $products .= "\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$stkd['cod']}</td>\r\n\t\t\t\t\t\t\t\t<td>{$stkd['des']}</td>\r\n\t\t\t\t\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t\t\t\t\t<td>{$pur['curr']} {$stkd['cunitcost']} or </td>\r\n\t\t\t\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\r\n\t\t\t\t\t\t\t\t<td>{$pur['curr']} {$stkd['duty']} or </td>\r\n\t\t\t\t\t\t\t\t<td>{$stkd['dutyp']}%</td>\r\n\t\t\t\t\t\t\t\t<td nowrap>{$pur['curr']} {$stkd['amt']}</td>\r\n\t\t\t\t\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get tax
    $tax = sprint($pur['tax']);
    /* --- End Some calculations --- */
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    list($dyear, $dmon, $dday) = explode("-", $pur['ddate']);
    /* -- Final Layout -- */
    $details = "\r\n\t\t\t\t\t<center>\r\n\t\t\t\t\t<h3>International Non-Stock Order Details</h3>\r\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border='0' width='95%'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Supplier</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['supplier']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Supplier Address</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><pre>{$pur['supaddr']}</pre></td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t</table>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td valign='top' align='right'>\r\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Order Details </th>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Non-Stock Order No.</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Order No.</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['ordernum']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Terms</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['terms']} Days</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Date</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pday}-{$pmon}-{$pyear}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Foreign Currency</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$currsel} &nbsp;&nbsp;Exchange rate {$pur['curr']} {$pur['xrate']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Tax</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} {$pur['tax']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Shipping Charges</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} {$pur['shipchrg']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Date</td>\r\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$dday}-{$dmon}-{$dyear}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t</table>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td colspan='2'>{$products}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<th width='40%'>Remarks</th>\r\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='15%'><br></td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td rowspan='4' align='center' valign='top'>" . nl2br($pur['remarks']) . "</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t</table>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td align='right'>\r\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' width='40%'>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\r\n\t\t\t\t\t\t\t\t\t\t<td align='right' nowrap>{$pur['curr']} {$pur['subtot']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges</td>\r\n\t\t\t\t\t\t\t\t\t\t<td align='right' nowrap>{$pur['curr']} {$pur['shipping']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td>Tax </td>\r\n\t\t\t\t\t\t\t\t\t\t<td align='right' nowrap>{$pur['curr']} {$pur['tax']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\r\n\t\t\t\t\t\t\t\t\t\t<td align='right' nowrap>{$pur['curr']} {$pur['total']}</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t</table>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t\t</form>\r\n\t\t\t\t\t</center>";
    return $details;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($noduty)) {
        $_POST["noduty"] = "yes";
    } else {
        $exd = "";
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    $v->isOk($supid, "num", 1, 20, "Please Select Supplier.");
    $v->isOk($terms, "num", 1, 5, "Invalid terms days.");
    $v->isOk($ipur_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($ipur_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($ipur_year, "num", 1, 5, "Invalid Date year.");
    $v->isOk($del_day, "num", 1, 2, "Invalid Delivery Date day.");
    $v->isOk($del_month, "num", 1, 2, "Invalid Delivery Date month.");
    $v->isOk($del_year, "num", 1, 5, "Invalid Delivery Date year.");
    //$v->isOk ($curr, "string", 1, 20, "Invalid Foreign currency.");
    $v->isOk($xrate, "float", 1, 20, "Invalid Exchange Rate.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Shipping Charges.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $pdate = mkdate($ipur_year, $ipur_month, $ipur_day);
    $v->isOk($pdate, "date", 1, 1, "Invalid purchase date.");
    $ddate = mkdate($del_year, $del_month, $del_day);
    $v->isOk($ddate, "date", 1, 1, "Invalid delivery date.");
    # Used to generate errors
    $error = "asa@";
    # Check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
        }
    }
    # Check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # Check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # Check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # Display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM 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>- Order 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;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    $pur['deptid'] = $sup['deptid'];
    # If supplier was just selected/changed, get the following
    if ($pur['supid'] != $supid) {
        $xrate = getRate($sup['fcid']);
    }
    # currency
    $currs = getSymbol($sup['fcid']);
    $curr = $currs['symbol'];
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $shipchrg += 0;
    $tax += 0;
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this Order
    $sql = "SELECT * FROM purint_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(ordered - qty)
        $sql = "UPDATE stock SET ordered = (ordered - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    # remove old items
    $sql = "DELETE FROM purint_items WHERE purid='{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # get selamt from selected stock
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    # Calculate the unitcost
                    if ($cunitcost[$keys] > 0) {
                        $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                    } else {
                        $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                    }
                    # Calculate the duty amount
                    if ($duty[$keys] < 1) {
                        if ($dutyp[$keys] > 0) {
                            $duty[$keys] = round($dutyp[$keys] / 100 * $cunitcost[$keys] / $xrate, 2);
                        }
                    } else {
                        if ($unitcost[$keys] > 0) {
                            $dutyp[$keys] = round($duty[$keys] * 100 / $cunitcost[$keys] * $xrate, 2);
                        } else {
                            $dutyp[$keys] = 0;
                        }
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                    # insert Order items
                    $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', '{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '{$ddate}', 'n', '" . USER_DIV . "')";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                    # update stock(ordered + qty)
                    $sql = "UPDATE stock SET ordered = (ordered + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            } else {
                # Get csprice from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the unitcost
                if ($cunitcost[$keys] > 0) {
                    $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                } else {
                    $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                }
                # Calculate the duty amount
                if ($duty[$keys] < 1) {
                    if ($dutyp[$keys] > 0) {
                        $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys] / $xrate, 2);
                    }
                } else {
                    if ($unitcost[$keys] > 0) {
                        $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys] * $xrate, 2);
                    } else {
                        $dutyp[$keys] = 0;
                    }
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                # Insert Order items
                $sql = "\n\t\t\t\t\tINSERT INTO purint_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tcunitcost, duty, dutyp, amt, ddate, recved, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$cunitcost[$keys]}', '{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '{$ddate}', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                # Update stock(ordered + qty)
                $sql = "UPDATE stock SET ordered = (ordered + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # Everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # Calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # shipchrg is in for curr
    $fshipchrg = $shipchrg;
    // $shipchrg = ($shipchrg * $xrate);
    # total
    $TOTAL = sprint($SUBTOT + $shipchrg + $tax);
    # total Duty
    if (isset($duty)) {
        $dutytot = sprint(array_sum($duty));
    } else {
        $dutytot = "0.00";
    }
    # Local Totals
    $LTOTAL = sprint($TOTAL * $xrate);
    $LSUBTOT = sprint($SUBTOT * $xrate);
    /* --- End Clac --- */
    # Insert Order to DB
    $sql = "\n\t\tUPDATE purch_int \n\t\tSET supid = '{$supid}', supaddr = '{$sup['supaddr']}', terms = '{$terms}', pdate = '{$pdate}', ddate = '{$ddate}',\n\t\t\tfcid = '{$sup['fcid']}', currency = '{$curr}', curr = '{$curr}', tax = '{$tax}', xrate = '{$xrate}', \n\t\t\tfshipchrg = '{$fshipchrg}', shipchrg = '{$shipchrg}', duty = '{$dutytot}', subtot = '{$SUBTOT}',\n\t\t\ttotal = '{$TOTAL}', balance = '{$TOTAL}', fsubtot = '{$LSUBTOT}', fbalance = '{$LTOTAL}', remarks = '{$remarks}',\n\t\t\tjobnum='{$delvat}', deptid = '{$dept['deptid']}' \n\t\tWHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $lastid = pglib_lastid("purch_int", "purid");
    // Was Done, Print and make another selected
    if (isset($donePrnt)) {
        $sql = "UPDATE purch_int SET done='y' WHERE purid='{$purid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.");
        $OUTPUT = "<script>printer('purch-int-det.php?purid={$lastid}');move('purch-int-new.php');</script>";
        return $OUTPUT;
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        # Insert Order to DB
        $sql = "UPDATE purch_int SET done = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New International Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Order from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a href='purch-int-det.php?purid={$lastid}'>Print Order</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($Cancel)) {
        db_connect();
        $Sl = "DELETE FROM sorders WHERE sordid='{$sordid}' AND cusnum=0 AND div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to delete Sales Order information");
        $sordid--;
        $Sql = "SELECT setval('sorders_sordid_seq', '{$sordid}')";
        $Rslt = db_exec($Sql) or errDie("Unable to set salesorder id.");
        header("Location: main.php");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($sordid, "num", 1, 20, "Invalid Sales Order Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "num", 0, 20, "Invalid order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($isord_day, "num", 1, 2, "Invalid Sales Order Date day.");
    $v->isOk($isord_month, "num", 1, 2, "Invalid Sales Order Date month.");
    $v->isOk($isord_year, "num", 1, 5, "Invalid Sales Order Date year.");
    $odate = $isord_year . "-" . $isord_month . "-" . $isord_day;
    if (!checkdate($isord_month, $isord_day, $isord_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Sales Order Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 16, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM sorders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li>- Sales Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    # check if Sales Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Sales Order number <b>{$sordid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM sord_data WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
        # currency
        $currs = getSymbol($cust['fcid']);
    } else {
        $cust = pg_fetch_array($custRslt);
        $sord['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($sord['cusnum'] != $cusnum) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
            $xrate = getRate($cust['fcid']);
        }
        # currency
        $currs = getSymbol($cust['fcid']);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$sord['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $traddisc += 0;
    $delchrg += 0;
    # insert Sales Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM sorders_items  WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    # remove old items
    $sql = "DELETE FROM sorders_items WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # get selamt from selected stock
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    # Calculate the unitcost
                    if ($cunitcost[$keys] > 0 && $unitcost[$keys] == 0) {
                        $unitcost[$keys] = $cunitcost[$keys] * $xrate;
                    } else {
                        $cunitcost[$keys] = $unitcost[$keys] / $xrate;
                    }
                    # Calculate amount
                    $funitcost[$keys] = $unitcost[$keys];
                    $famt[$keys] = $qtys[$keys] * ($funitcost[$keys] - $disc[$keys]);
                    # Calculate amount
                    // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                    $unitcost[$keys] = sprint($funitcost[$keys] / $xrate);
                    $amt[$keys] = sprint($famt[$keys] / $xrate);
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $taxex += $amt[$keys];
                    }
                    $wtd = $whids[$keys];
                    # insert Sales Order items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO sorders_items (\n\t\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tfunitcost, amt, famt, disc, discp, \n\t\t\t\t\t\t\tdiv\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$funitcost[$keys]}', '{$amt[$keys]}', '{$famt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', \n\t\t\t\t\t\t\t'" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Sales Order items to Cubit.", SELF);
                    # update stock(alloc + qty)
                    $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            } else {
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate the unitcost
                if ($cunitcost[$keys] > 0 && $unitcost[$keys] == 0) {
                    $unitcost[$keys] = $cunitcost[$keys] * $xrate;
                } else {
                    $cunitcost[$keys] = $unitcost[$keys] / $xrate;
                }
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                }
                # Calculate amount
                $funitcost[$keys] = $unitcost[$keys];
                $famt[$keys] = $qtys[$keys] * ($funitcost[$keys] - $disc[$keys]);
                # Calculate amount
                // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                $unitcost[$keys] = sprint($funitcost[$keys] / $xrate);
                $amt[$keys] = sprint($famt[$keys] / $xrate);
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes') {
                    $taxex += $amt[$keys];
                }
                $wtd = $whids[$keys];
                # insert Sales Order items
                $sql = "\n\t\t\t\t\tINSERT INTO sorders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tfunitcost, amt, famt, disc, discp, \n\t\t\t\t\t\tdiv\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$funitcost[$keys]}', '{$amt[$keys]}', '{$famt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', \n\t\t\t\t\t\t'" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Sales Order items to Cubit.", SELF);
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(($subtotal - $taxex) * $VATP / 100);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(($subtotal - $taxex) * $VATP / (100 + $VATP));
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    	# calculate subtot
    	$SUBTOT = 0.00;
    	if(isset($amt))
    		$SUBTOT = array_sum($amt);
    
    	$SUBTOT -= $taxex;
    
    	# duplicate
    	$SUBTOTAL = $SUBTOT;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "exc"){
    		$SUBTOTAL = $SUBTOTAL;
    		$delexvat= ($delchrg);
    	}elseif($chrgvat == "inc"){
    		$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    		$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    	}else{
    		$SUBTOTAL = ($SUBTOTAL);
    		$delexvat = ($delchrg);
    	}
    
    	$SUBTOT = $SUBTOTAL;
    	$EXVATTOT = $SUBTOT;
    	$EXVATTOT += $delexvat;
    
    	# Minus trade discount from taxex
    	if($traddisc > 0){
    		$traddiscmtt = (($traddisc/100) * $taxex);
    	}else{
    		$traddiscmtt = 0;
    	}
    	$taxext = ($taxex - $traddiscmtt);
    
    	if($traddisc > 0) {
    		$traddiscmt = ($EXVATTOT * ($traddisc/100));
    	}else{
    		$traddiscmt = 0;
    	}
    	$EXVATTOT -= $traddiscmt;
    	// $EXVATTOT -= $taxex;
    
    	$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    	if($chrgvat != "nov"){
    		$VAT = sprint($EXVATTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    	$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    # insert Sales Order to DB
    $sql = "\n\t\tUPDATE sorders \n\t\tSET cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', deptid = '{$dept['deptid']}', cusacc = '{$cust['accno']}', \n\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', cusvatno = '{$cust['vatnum']}', \n\t\t\tcordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', \n\t\t\tfcid = '{$cust['fcid']}', currency = '{$currs['symbol']}', xrate = '{$xrate}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', \n\t\t\tlocation = '{$cust['location']}', discount = '{$traddiscmt}', delivery = '{$delexvat}' \n\t\tWHERE sordid = '{$sordid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM sord_data WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\tINSERT INTO sord_data (\n\t\t\tsordid, dept, customer, addr1, div\n\t\t) VALUES (\n\t\t\t'{$sordid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Sales Order data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # insert Sales Order to DB
        $sql = "UPDATE sorders SET done = 'y' WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Sales Order status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New International Sales Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Sales Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New International Sales Order Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Sales Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='sorder-view.php'>View Sales Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function getAvgVol()
{
    require_once '/home/stocksloper/db.inc';
    $deletedata = mysql_query("truncate table avgvolume") or trigger_error(mysql_error());
    # Get a symbol
    $stocks = getSymbol();
    foreach ($stocks as $stock) {
        $symbol = $stock['symbol'];
        #dbg
        #	$symbol = 'AAPL';
        #echo $symbol."\n";
        # Grab the data from Yahoo Finance
        $avgvolume = "";
        #dbg
        $csv = "http://download.finance.yahoo.com/d/quotes.csv?s={$symbol}&f=a2";
        $volume = curl($csv);
        #print_r($volume);
        #dbg
        #echo $symbol . ",". $volume."\n";
        $putstock = mysql_query("insert into avgvolume (symbol,volume) values ('{$symbol}','{$volume}')") or trigger_error(mysql_error());
    }
    //foreach stocks
}
function alloc($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    if ($amt < 0.01) {
        $v->isOk($amt, "float", 5, 1, "Amount to small.");
    }
    $v->isOk($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return method($_POST, $confirm);
    }
    $rate += 0;
    if ($rate == 0) {
        $rate = 1;
    }
    # Get bank account name
    db_connect();
    $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    # Supplier name
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    $currs = getSymbol($sup['fcid']);
    if ($bank['btype'] == 'int') {
        $bcur = $currs['symbol'];
        $amt = sprint($amt);
        $lamt = sprint($amt * $rate);
    } else {
        $lamt = sprint($amt);
        $amt = sprint($amt / $rate);
        $bcur = CUR;
    }
    $out = 0;
    $rate = sprint($rate);
    $confirm = "\n\t\t\t<h3>New International Bank Receipt</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t\t<input type='hidden' name='supid' value='{$supid}'>\n\t\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t\t<input type='hidden' name='rate' value='{$rate}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Field</th>\n\t\t\t\t\t<th>Value</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account</td>\n\t\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Paid To</td>\n\t\t\t\t\t<td valign='center'>({$sup['supno']}) {$sup['supname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Description</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($descript) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Amount</td>\n\t\t\t\t\t<td valign='center'>{$sup['currency']} {$amt} | " . CUR . " {$lamt}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Exchange rate</td>\n\t\t\t\t\t<td valign='center'>" . CUR . " / {$sup['currency']} {$rate}</td>\n\t\t\t\t</tr>";
    if ($all == 0) {
        $out = $amt;
        // Connect to database
        db_connect();
        $sql = "SELECT purid as invid,intpurid as invid2,fbalance,pdate as odate FROM suppurch WHERE supid = '{$supid}' AND fbalance > 0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql) or errDie("unable to get invoices.");
        $i = 0;
        while ($inv = pg_fetch_array($prnInvRslt) and $out > 0) {
            //if ($inv['invid']==0) {continue;}
            if ($inv['invid2'] > 0) {
                $inv['invid'] = $inv['invid2'];
            }
            if ($i == 0) {
                $confirm .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'><br></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'><h3>Outstanding Purchases</h3></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<th>Purchase</th>\n\t\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t</tr>";
            }
            $invid = $inv['invid'];
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invid']}</td>\n\t\t\t\t\t\t<td>{$sup['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>";
            if ($out >= $inv['fbalance']) {
                $val = $inv['fbalance'];
                $out = $out - $inv['fbalance'];
            } else {
                $val = $out;
                $out = 0;
            }
            $i++;
            $confirm .= "\n\t\t\t\t\t\t<td><input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>{$sup['currency']} {$val}</td>\n\t\t\t\t\t</tr>";
        }
        if ($out > 0) {
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='5'><b>A general transaction will debit the supplier's account with {$sup['currency']} {$out} </b></td>\n\t\t\t\t\t</tr>";
        }
    }
    if ($all == 1) {
        $confirm .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Current</th>\n\t\t\t\t\t\t\t\t<th>30 days</th>\n\t\t\t\t\t\t\t\t<th>60 days</th>\n\t\t\t\t\t\t\t\t<th>90 days</th>\n\t\t\t\t\t\t\t\t<th>120 days</th>\n\t\t\t\t\t\t\t\t<th>Total Outstanding</th>\n\t\t\t\t\t\t\t</tr>";
        $curr = sage($supid, 29);
        $age30 = sage($supid, 59);
        $age60 = sage($supid, 89);
        $age90 = sage($supid, 119);
        $age120 = sage($supid, 149);
        $supttot = $curr + $age30 + $age60 + $age90 + $age120;
        # Alternate bgcolor
        $confirm .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($curr) . "</td>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($age30) . "</td>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($age60) . "</td>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($age90) . "</td>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($age120) . "</td>\n\t\t\t\t\t\t\t\t<td>{$sup['currency']} " . sprint($supttot) . "</td>\n\t\t\t\t\t\t\t</tr>";
        $confirm .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='text' size='7' name='out1'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='7' name='out2'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='7' name='out3'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='7' name='out4'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='7' name='out5'></td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t</tr>";
        $confirm .= "\n\t\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>";
    }
    if ($all == 2) {
        db_connect();
        $sql = "SELECT purid as invid,intpurid as invid2,fbalance,pdate as odate FROM suppurch WHERE supid = '{$supid}' AND fbalance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        if (pg_numrows($prnInvRslt) < 1) {
            return "The selected supplier has no outstanding purchases<br>\n\t\t\t\tTo make a payment in advance please select Auto Allocation";
        }
        $i = 0;
        while ($inv = pg_fetch_array($prnInvRslt)) {
            if ($inv['invid'] == 0) {
                continue;
            }
            if ($inv['invid2'] > 0) {
                $inv['invid'] = $inv['invid2'];
            }
            if ($i == 0) {
                $confirm .= "\n\t\t\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'><h3>Outstanding Purchases</h3></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<th>Purchase</th>\n\t\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t</tr>";
            }
            $invid = $inv['invid'];
            $val = '';
            if (pg_numrows($prnInvRslt) == 1) {
                $val = $amt;
            }
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invid']}</td>\n\t\t\t\t\t\t<td>{$sup['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>";
            $i++;
            $confirm .= "\n\t\t\t\t\t\t<td><input type='text' name='paidamt[{$invid}]' size='10' value='{$val}'></td>\n\t\t\t\t\t</tr>";
        }
        if ($out > 0) {
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='5'><b>A general transaction will debit the supplier's account with {$sup['currency']} {$out} </b></td>\n\t\t\t\t\t</tr>";
        }
    }
    $confirm .= "\n\t\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='bank-pay-supp.php'>Add supplier payment</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $confirm;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        enter($_POST);
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    if (isset($fcids)) {
        foreach ($fcids as $key => $value) {
            $v->isOk($fcids[$key], "num", 1, 20, "Invalid currency.");
            $v->isOk($rates[$key], "float", 1, 20, "Invalid rate.");
        }
    }
    # Display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    foreach ($fcids as $key => $fcid) {
        $cur = getSymbol($fcid);
        $rates[$key] = sprint($rates[$key]);
        xrate_change($fcid, $rates[$key]);
        // Main updates
        sup_xrate_update($fcid, $rates[$key]);
        xrate_update($fcid, $rates[$key], "suppurch", "id");
        cus_xrate_update($fcid, $rates[$key]);
        xrate_update($fcid, $rates[$key], "invoices", "invid");
        xrate_update($fcid, $rates[$key], "custran", "id");
        bank_xrate_update($fcid, $rates[$key]);
    }
    // Layout
    $write = "\r\n\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t\t\t<tr><th>Exchange rates have been updated</th></tr>\r\n\t\t\t<tr class='datacell'><td>Exchange rates have been successfully updated on the system.</td></tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\r\n\t\t\t<tr><th>Quick Links</th></tr>\r\n\t\t\t<tr class='bg-odd'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write;
}
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 write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return edit_err($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($deptid, "num", 1, 255, "Invalid Department.");
    $v->isOk($supid, "num", 1, 50, "Invalid supplier id.");
    $v->isOk($supno, "string", 1, 255, "Invalid suppleir number.");
    $v->isOk($supname, "string", 1, 255, "Invalid supplier name.");
    $v->isOk($loc, "string", 1, 3, "Invalid Type.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($vatnum, "string", 1, 255, "Invalid supplier vat number.");
    $v->isOk($registration, "string", 1, 255, "Invalid registration number.");
    $v->isOk($supaddr, "string", 1, 255, "Invalid supplier address.");
    $v->isOk($suppostaddr, "string", 0, 255, "Invalid supplier postal address.");
    $v->isOk($contname, "string", 1, 255, "Invalid contact name.");
    $v->isOk($tel, "string", 1, 20, "Invalid tel no.");
    $v->isOk($fax, "string", 0, 20, "Invalid fax no.");
    $v->isOk($cell, "string", 0, 20, "Invalid cell no.");
    $v->isOk($email, "email", 0, 255, "Invalid e-mail address.");
    $v->isOk($listid, "num", 1, 20, "Invalid price list.");
    $v->isOk($url, "url", 0, 255, "Invalid web address.");
    $v->isOk($bankname, "string", 0, 255, "Invalid bank name.");
    $v->isOk($branname, "string", 0, 255, "Invalid branch name.");
    $v->isOk($brancode, "string", 0, 255, "Invalid branch code.");
    $v->isOk($bankaccname, "string", 0, 255, "Invalid bank account name.");
    $v->isOk($bankacctype, "string", 0, 255, "Invalid bank account type.");
    $v->isOk($bankaccno, "num", 0, 255, "Invalid bank account number.");
    $v->isOk($comments, "string", 0, 255, "Invalid characters in comment.");
    $v->isOk($branch, "string", 0, 255, "Invalid supplier branch.");
    $v->isOk($reference, "string", 0, 255, "Invalid reference.");
    $v->isOk($bee_status, "string", 0, 255, "Invalid BEE Status");
    $v->isOk($supp_grp, "num", 1, 9, "Invalid supplier group selected.");
    $v->isOk($team_id, "num", 1, 9, "Invalid team selection.");
    $v->isOk($setdisc, "float", 1, 40, "Invalid Settlement Discount Amount.");
    $v->isOk($setdays, "num", 1, 40, "Invalid Settlement Discount Days");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM suppliers WHERE supno='{$supno}' AND supid!='{$supid}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        return edit_err($_POST, "<li class='err'>There is already a supplier with that number.</li>");
    }
    # connect to db
    db_connect();
    $curr = getSymbol($fcid);
    # write to db
    $sql = "\r\n\t\tUPDATE suppliers \r\n\t\tSET \r\n\t\t\tdeptid = '{$deptid}', supno = '{$supno}', supname = '{$supname}', vatnum = '{$vatnum}', supaddr = '{$supaddr}', \r\n\t\t\tsuppostaddr = '{$suppostaddr}', contname = '{$contname}', tel = '{$tel}', fax = '{$fax}', cell = '{$cell}', \r\n\t\t\temail = '{$email}', url = '{$url}', listid = '{$listid}', bankname = '{$bankname}', branname = '{$branname}', \r\n\t\t\tbrancode = '{$brancode}', bankaccno = '{$bankaccno}', location = '{$loc}', fcid = '{$fcid}', currency = '{$curr['symbol']}', \r\n\t\t\tcomments = '{$comments}', branch = '{$branch}', reference = '{$reference}', bee_status = '{$bee_status}', \r\n\t\t\tregistration = '{$registration}', bankaccname = '{$bankaccname}', bankacctype = '{$bankacctype}', \r\n\t\t\tteam_id = '{$team_id}', setdisc = '{$setdisc}', setdays = '{$setdays}' \r\n\t\tWHERE supid  = '{$supid}'";
    $suppRslt = db_exec($sql) or errDie("Unable to edit supplier on the system.", SELF);
    if (pg_cmdtuples($suppRslt) < 1) {
        return "<li class='err'>Unable to Edit supplier in database.</li>";
    }
    // Update documents
    $sql = "SELECT * FROM crm.stmp_docs WHERE session='{$_REQUEST['CUBIT_SESSION']}'";
    $stdoc_rslt = db_exec($sql) or errDie("Unable to retrieve docs.");
    while ($stdoc_data = pg_fetch_array($stdoc_rslt)) {
        $sql = "\r\n\t\t\tINSERT INTO crm.supplier_docs (\r\n\t\t\t\tsupid, file, type, filename, size, real_filename\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$supid}', '{$stdoc_data['file']}', '{$stdoc_data['type']}', '{$stdoc_data['filename']}', '{$stdoc_data['size']}', '{$stdoc_data['real_filename']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to save files to customer.");
        $sql = "DELETE FROM crm.stmp_docs WHERE id='{$stdoc_data['id']}'";
        db_exec($sql) or errDie("Unable to remove tmp file.");
    }
    #handle supplier groups
    if ($supp_grp != 0) {
        #group set, check whether we should add the new entry or update a existing one ...
        $check_grp = "SELECT * FROM supp_grpowners WHERE supid = '{$supid}' LIMIT 1";
        $run_check = db_exec($check_grp) or errDie("Unable to get supplier group information.");
        if (pg_numrows($run_check) < 1) {
            $insert_sql = "INSERT INTO supp_grpowners (grpid,supid) VALUES ('{$supp_grp}','{$supid}')";
            $run_insert = db_exec($insert_sql) or errDie("Unable to add supplier group information.");
        } else {
            $update_sql = "UPDATE supp_grpowners SET grpid = '{$supp_grp}' WHERE supid = '{$supid}'";
            $run_update = db_exec($update_sql) or errDie("Unable to update supplier group information");
        }
    } else {
        #remove any current entry
        $remove_sql = "DELETE FROM supp_grpowners WHERE supid = '{$supid}'";
        $run_remove = db_exec($remove_sql) or errDie("Unable to update supplier group informatiom");
    }
    // update the contact in the contact list if any
    $sql = "UPDATE cons SET surname='{$supname}', tell='{$tel}', fax='{$fax}', email='{$email}', padd='{$supaddr}' WHERE supp_id = '{$supid}'";
    $rslt = db_exec($sql) or errDie("Unable to edit supplier in contact list.", SELF);
    return edit($supid, "<li class='yay'>Supplier <b>{$supname}</b>, has been saved.</li><br>");
    //	$write = "
    //		<table ".TMPL_tblDflts." width='50%'>
    //			<tr>
    //				<th>Supplier edited</th>
    //			</tr>
    //			<tr class='datacell'>
    //				<td>Supplier <b>$supname</b>, has been edited.</td>
    //			</tr>
    //		</table>
    //		<p>
    //		<table border=0 cellpadding='2' cellspacing='1'>
    //			<tr>
    //				<th>Quick Links</th>
    //			</tr>
    //			<tr class='".bg_class()."'>
    //				<td><a href='supp-view.php'>View Suppliers</a></td>
    //			</tr>
    //			<tr class='".bg_class()."'>
    //				<td><a href='main.php'>Main Menu</a></td>
    //			</tr>
    //		</table>";
    //	return $write;
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankname, "string", 1, 50, "Invalid Bank name.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($branchname, "string", 1, 50, "Invalid Branch Name.");
    $v->isOk($branchcode, "string", 1, 15, "Invalid Branch Code.");
    $v->isOk($accname, "string", 1, 50, "Invalid Account Name.");
    $v->isOk($accnum, "num", 1, 30, "Invalid Account Number.");
    $v->isOk($accid, "num", 1, 20, "Invalid Ledger Account.");
    $v->isOk($cardnum, "num", 1, 16, "Invalid Card Number.");
    $v->isOk($mon, "num", 1, 2, "Invalid Expiry date.");
    $v->isOk($year, "num", 1, 4, "Invalid Expiry date.");
    $v->isOk($lastdigits, "num", 1, 3, "Invalid Last Digits.");
    $v->isOk($cardtyp, "string", 1, 255, "Invalid Card Type.");
    $v->isOk($details, "string", 1, 255, "Invalid Details.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        return view($_POST, $confirm);
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $curr = getSymbol($fcid);
    db_connect();
    # Register bank account
    $sql = "INSERT INTO bankacct (type, acctype, bankname, btype, fcid, currency, branchname, branchcode, accname, accnum, cardnum, mon, year, digits, cardtype,details, div)\n\tVALUES ('ptrl', 'Petrol Card', '{$bankname}', '{$loc}', '{$fcid}', '{$curr['name']}', '{$branchname}', '{$branchcode}', '{$accname}', '{$accnum}', '{$cardnum}', '{$mon}', '{$year}', '{$lastdigits}', '{$cardtyp}', '{$details}', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank account to database.");
    # Get last id from bank accounts
    $bankid = pglib_lastid("cubit.bankacct", "bankid");
    # Create hook
    core_connect();
    $hook = "INSERT INTO bankacc(accid, accnum, div) VALUES('{$bankid}', '{$accid}', '" . USER_DIV . "')";
    $Rlst = db_exec($hook) or errDie("Unable to add hook for for new bank account", SELF);
    # Status report
    $write = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>New Petrol Card Account added to database</th></tr>\n\t\t<tr class=datacell><td>New Petrol Card Account {$accname}, bas been successfully added to Cubit.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='bankacct-view.php'>View Bank Accounts</a></td></tr>\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n\t</table>";
    return $write;
}
===

Grabs stock symbol from database using getSymbol function
Gets history of stock from getHistory function
Does slope analysis using getSlope function

Starts with 120 days and keeps going until 2500 days

***/
# Put stuff in a log
$log = new Loggy();
$log->lfile('logstock.log');
# Delete previous slope data
deleteSlopeData();
# minimum trading days for slope analysis
$ntd = 120;
# look up stocks in stock_symbol_name table
$stocks = getSymbol();
foreach ($stocks as $stock) {
    $symbol = $stock['symbol'];
    # look up # of trading days stock traded
    $days = getDays($symbol);
    if ($days === 0 || $days < 500) {
        continue;
    } else {
        getRecursive($symbol, $ntd);
    }
    //else days
}
//foreach stocks
function write($_POST)
{
    # Get vars
    global $_POST;
    extract($_POST);
    if (isset($back)) {
        return enter();
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($deptid, "num", 1, 255, "Invalid Department.");
    $v->isOk($supno, "string", 1, 255, "Invalid supplier number.");
    $v->isOk($supname, "string", 1, 255, "Invalid supplier name.");
    $v->isOk($loc, "string", 1, 3, "Invalid Type.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($vatnum, "string", 1, 255, "Invalid supplier vat number.");
    $v->isOk($registration, "string", 1, 255, "Invalid registration/id number.");
    $v->isOk($supaddr, "string", 1, 255, "Invalid supplier address.");
    $v->isOk($suppostaddr, "string", 0, 255, "Invalid supplier postal address.");
    $v->isOk($contname, "string", 1, 255, "Invalid contact name.");
    $v->isOk($tel, "string", 1, 20, "Invalid tel no.");
    $v->isOk($fax, "string", 0, 20, "Invalid fax no.");
    $v->isOk($cell, "string", 0, 20, "Invalid cell no.");
    $v->isOk($email, "email", 0, 255, "Invalid e-mail address.");
    $v->isOk($url, "url", 0, 255, "Invalid web address.");
    $v->isOk($listid, "num", 1, 20, "Invalid price list.");
    $v->isOk($bankname, "string", 0, 255, "Invalid bank name.");
    $v->isOk($branname, "string", 0, 255, "Invalid branch name.");
    $v->isOk($brancode, "string", 0, 255, "Invalid branch code.");
    $v->isOk($bankaccname, "string", 0, 255, "Invalid bank account name.");
    $v->isOk($bankacctype, "string", 0, 255, "Invalid bank account type.");
    $v->isOk($bankaccno, "num", 0, 255, "Invalid bank account number.");
    $v->isOk($lead_source, "num", 0, 9, "Invalid lead source selected.");
    $v->isOk($comments, "string", 0, 255, "Invalid characters in comment.");
    $v->isOk($supbranch, "string", 0, 255, "Invalid supplier branch.");
    $v->isOk($reference, "string", 0, 255, "Invalid references.");
    $v->isOk($bee_status, "string", 0, 255, "Invalid BEE Status");
    $v->isOk($team_id, "num", 1, 9, "Invalid team selection.");
    $v->isOk($supp_grp, "num", 1, 9, "Invalid supplier group selected.");
    $v->isOk($setdisc, "float", 1, 40, "Invalid Settlement Discount Amount.");
    $v->isOk($setdays, "num", 1, 40, "Invalid Settlement Discount Days");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM suppliers WHERE supno='{$supno}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        return enter("<li class='err'>Supplier number exists.</li>");
    }
    # Connect to db
    db_connect();
    $curr = getSymbol($fcid);
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add supplier to database. (TB)</li>";
    }
    # Write to db
    $sql = "\n\t\tINSERT INTO suppliers (\n\t\t\tdeptid, supno, supname, location, fcid, \n\t\t\tcurrency, vatnum, supaddr, suppostaddr, contname, tel, \n\t\t\tfax, cell, email, url, listid, bankname, \n\t\t\tbranname, brancode, bankaccno, balance, fbalance, \n\t\t\tdiv, lead_source, comments, branch, bee_status, \n\t\t\treference, team_id, registration, bankaccname, bankacctype, \n\t\t\tsetdisc, setdays\n\t\t) VALUES (\n\t\t\t'{$deptid}', '{$supno}', '{$supname}', '{$loc}', '{$fcid}', \n\t\t\t'{$curr['symbol']}', '{$vatnum}', '{$supaddr}', '{$suppostaddr}', '{$contname}', '{$tel}', \n\t\t\t'{$fax}', '{$cell}', '{$email}', '{$url}', '{$listid}', '{$bankname}', \n\t\t\t'{$branname}', '{$brancode}', '{$bankaccno}', 0, 0, \n\t\t\t'" . USER_DIV . "', '{$lead_source}', '{$comments}', '{$supbranch}', '{$bee_status}', \n\t\t\t'{$reference}', '{$team_id}', '{$registration}', '{$bankaccname}', '{$bankacctype}', \n\t\t\t'{$setdisc}', '{$setdays}'\n\t\t)";
    $supRslt = db_exec($sql) or errDie("Unable to add supplier to the system.", SELF);
    if (pg_cmdtuples($supRslt) < 1) {
        return "<li class='err'>Unable to add supplier to database.</li>";
    }
    if (($supp_id = pglib_lastid("suppliers", "supid")) == 0) {
        return "<li class='err'>Unable to add supplier to contact list.</li>";
    }
    #handle supplier groups
    if ($supp_grp != 0) {
        $insert_sql = "INSERT INTO supp_grpowners (grpid,supid) VALUES ('{$supp_grp}','{$supp_id}')";
        $run_insert = db_exec($insert_sql) or errDie("Unable to add supplier group information.");
    }
    # Check if should be added to contact list
    db_connect();
    $sql = "\n\t\tINSERT INTO cons (\n\t\t\tname, surname, comp, ref, tell, cell, \n\t\t\tfax, email, hadd, padd, date, supp_id, \n\t\t\tcon, by, div\n\t\t) VALUES (\n\t\t\t'{$contname}', '{$supname}', '', 'Supplier', '{$tel}', '{$cell}', \n\t\t\t'{$fax}', '{$email}', '{$supaddr}', '{$suppostaddr}', CURRENT_DATE, '{$supp_id}', \n\t\t\t'No', '" . USER_NAME . "','" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to add supplier to contact list.", SELF);
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add supplier to database. (TC)</li>";
    }
    $Date = date("Y-m-d");
    $qryi = new dbUpdate();
    for ($i = 1; $i <= 12; ++$i) {
        $qryi->setTable("suppledger", "{$i}");
        $cols = grp(m("supid", $supp_id), m("contra", "0"), m("edate", $Date), m("sdate", $Date), m("eref", "0"), m("descript", "Balance"), m("credit", "0"), m("debit", "0"), m("div", USER_DIV), m("dbalance", "0"), m("cbalance", "0"));
        $qryi->setCols($cols);
        $qryi->run(DB_INSERT);
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$supname}");
        exit;
    }
    if ($re != "no") {
        db_conn('cubit');
        $re += 0;
        $Sl = "UPDATE purchases SET supid='{$supp_id}' WHERE purid='{$re}'";
        $Ri = db_exec($Sl);
        //print $Sl;exit;
        header("Location: purchase-new.php?purid={$re}&cont=1&letters=");
        exit;
    }
    // Update documents
    $sql = "SELECT * FROM crm.stmp_docs WHERE session='{$_REQUEST['CUBIT_SESSION']}'";
    $stdoc_rslt = db_exec($sql) or errDie("Unable to retrieve docs.");
    while ($stdoc_data = pg_fetch_array($stdoc_rslt)) {
        $sql = "\n\t\t\tINSERT INTO crm.supplier_docs (\n\t\t\t\tsupid, file, type, filename, size, \n\t\t\t\treal_filename\n\t\t\t) VALUES (\n\t\t\t\t'{$supp_id}', '{$stdoc_data['file']}', '{$stdoc_data['type']}', '{$stdoc_data['filename']}', '{$stdoc_data['size']}', \n\t\t\t\t'{$stdoc_data['real_filename']}'\n\t\t\t)";
        db_exec($sql) or errDie("Unable to save files to customer.");
        $sql = "DELETE FROM crm.stmp_docs WHERE id='{$stdoc_data['id']}'";
        db_exec($sql) or errDie("Unable to remove tmp file.");
    }
    $sql = "SELECT * FROM cubit.cons WHERE supp_id='{$supp_id}'";
    $con_rslt = db_exec($sql) or errDie("Unable to retrieve contact.");
    $con_data = pg_fetch_array($con_rslt);
    if (pg_num_rows($con_rslt)) {
        $con_out = "<a href='javascript:popupOpen(\"groupware/conper-add.php?type=conn&id={$con_data['id']}\")'>\n\t\t\tAdd Sub Contact\n\t\t</a>";
    } else {
        $con_out = "";
    }
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Supplier added to the system</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>New Supplier <b>{$supname}</b>, has been successfully added to the system. {$con_out}</td>\n\t\t\t</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='supp-new.php'>Add Supplier</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='supp-view.php'>View Suppliers</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 $write;
    $_POST = array();
    return enter("<li class='yay'>Supplier added to the system. {$con_out}</li><br>");
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return enter_err($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($deptid, "num", 1, 255, "Invalid Department.");
    $v->isOk($supno, "string", 1, 255, "Invalid supplier number.");
    $v->isOk($supname, "string", 1, 255, "Invalid supplier name.");
    $v->isOk($loc, "string", 1, 3, "Invalid Type.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($supaddr, "string", 1, 255, "Invalid supplier address.");
    $v->isOk($contname, "string", 1, 255, "Invalid contact name.");
    $v->isOk($tel, "string", 1, 20, "Invalid tel no.");
    $v->isOk($fax, "string", 0, 20, "Invalid fax no.");
    $v->isOk($listid, "num", 1, 20, "Invalid price list.");
    $v->isOk($bee_training, "string", 0, 255, "Invalid BEE Status");
    $v->isOk($comments, "string", 0, 255, "Invalid Notes");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM suppliers WHERE supno='{$supno}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        return enter_err($_POST, "<li class='err'>There is already a supplier with that number.</li>");
    }
    # Connect to db
    db_connect();
    $curr = getSymbol($fcid);
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add supplier to database. (TB)</li>";
    }
    # Write to db
    $sql = "INSERT INTO  suppliers(deptid, supno, supname, location, fcid, currency, supaddr, contname, tel, fax, listid, balance, fbalance, div, bee_training, comments)\r\n\tVALUES ('{$deptid}', '{$supno}', '{$supname}', '{$loc}', '{$fcid}', '{$curr['symbol']}', '{$supaddr}', '{$contname}', '{$tel}', '{$fax}', '{$listid}', 0, 0, '" . USER_DIV . "', '{$bee_training}', '{$comments}')";
    $supRslt = db_exec($sql) or errDie("Unable to add supplier to the system.", SELF);
    if (pg_cmdtuples($supRslt) < 1) {
        return "<li class='err'>Unable to add supplier to database.</li>";
    }
    if (($supp_id = pglib_lastid("suppliers", "supid")) == 0) {
        return "<li class='err'>Unable to add supplier to contact list.</li>";
    }
    # Check if should be added to contact list
    db_connect();
    $sql = "INSERT INTO cons (name,surname,comp,ref,tell,cell,fax,hadd,padd,date,supp_id,con,by,div)\r\n\tVALUES ('{$contname}','{$supname}','','Supplier','{$tel}','','{$fax}','{$supaddr}','',CURRENT_DATE, '{$supp_id}', 'No', '" . USER_NAME . "','" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to add supplier to contact list.", SELF);
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add supplier to database. (TC)</li>";
    }
    $Date = date("Y-m-d");
    db_conn('audit');
    $Sl = "SELECT * FROM closedprd ORDER BY id";
    $Ri = db_exec($Sl);
    while ($pd = pg_fetch_array($Ri)) {
        db_conn($pd['prdnum']);
        $Sl = "INSERT INTO suppledger(supid,contra,edate,sdate,eref,descript,credit,debit,div,dbalance,cbalance) VALUES \r\n\t\t('{$supp_id}','0','{$Date}','{$Date}','0','Balance','0','0','" . USER_DIV . "','0','0')";
        $Rj = db_exec($Sl) or errDie("Unable to insert cust balances");
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$supname}");
        exit;
    }
    if ($re != "no") {
        db_conn('cubit');
        $re += 0;
        $Sl = "UPDATE purchases SET supid='{$supp_id}' WHERE purid='{$re}'";
        $Ri = db_exec($Sl);
        //print $Sl;exit;
        header("Location: purchase-new.php?purid={$re}&cont=1&letters=");
        exit;
    }
    $write = "\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Supplier added to the system</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td>New Supplier <b>{$supname}</b>, has been successfully added to the system.</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='supp-new.php'>Add Supplier</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='supp-view.php'>View Suppliers</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>";
    return $write;
}
function printStmnt()
{
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class=err>There are no customers found.";
    }
    /* Start PDF Layout */
    include "../pdf-settings.php";
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    # put a line top and bottom on all the pages
    $all = $pdf->openObject();
    $pdf->saveState();
    $pdf->setStrokeColor(0, 0, 0, 1);
    # Heading
    $pdf->ezText("<b>Customer Monthly Statement</b>", $set_txtSize + 2, array('justification' => 'centre'));
    $pdf->line(20, 40, 578, 40);
    # $pdf->line(20,822,578,822);
    $pdf->addText(20, 34, 6, 'Cubit Accounting');
    $pdf->restoreState();
    $pdf->closeObject();
    # note that object can be told to appear on just odd or even pages by changing 'all' to 'odd'
    # or 'even'.
    $pdf->addObject($all, 'all');
    /* End PDF Layout */
    $i = 0;
    while ($cust = pg_fetch_array($custRslt)) {
        $cusnum = $cust['cusnum'];
        $stmnt = array();
        $cusdet = array();
        $baldat = array();
        $currs = getSymbol($cust['fcid']);
        $curr = $currs['symbol'];
        # Create a new page for customer
        if ($i > 0) {
            $pdf->newPage();
        }
        # connect to database
        db_connect();
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $stmnt = array();
        $totout = 0;
        if (!open()) {
            # Query server
            $sql = "SELECT * FROM stmnt WHERE cusnum = '{$cusnum}' AND date >= '{$fdate}' AND div = '" . USER_DIV . "' ORDER BY date ASC";
            $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        } else {
            # Query server
            $sql = "SELECT * FROM open_stmnt WHERE cusnum = '{$cusnum}' AND balance != '0' AND div = '" . USER_DIV . "' ORDER BY date ASC";
            $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        }
        if (pg_numrows($stRslt) < 1) {
            $stmnt[] = array('date' => "No previous invoices/transactions for this month.", 'invid' => " ", 'type' => " ", 'amount' => " ");
        } else {
            while ($st = pg_fetch_array($stRslt)) {
                # format date
                $st['date'] = explode("-", $st['date']);
                $st['date'] = $st['date'][2] . "-" . $st['date'][1] . "-" . $st['date'][0];
                $st['amount'] = sprint($st['amount']);
                if (substr($st['type'], 0, 7) == "Invoice") {
                    $ex = "INV";
                } elseif (substr($st['type'], 0, 17) == "Non-Stock Invoice") {
                    $ex = "INV";
                } elseif (substr($st['type'], 0, 21) == "Non Stock Credit Note") {
                    $ex = "CR";
                } elseif (substr($st['type'], 0, 11) == "Credit Note") {
                    $ex = "CR";
                } else {
                    $ex = "";
                }
                $stmnt[] = array('date' => $st['date'], 'invid' => $ex . " " . $st['invid'], 'type' => $st['type'], 'amount' => $curr . " {$st['amount']}");
                # keep track of da totals
                $totout += $st['amount'];
            }
        }
        $balbf = $cust['balance'] - $totout;
        $balbf = sprint($balbf);
        $cust['balance'] = sprint($cust['balance']);
        $stmnthead = array('date' => "Date", 'invid' => "Ref No.", 'type' => "Details", 'amount' => "Amount");
        /* start PDF Layout */
        # Heading
        // $pdf->ezText("<b>Customer Monthly Statement</b>", $set_txtSize+2, array('justification'=>'centre'));
        # Set y so its away from the top
        $pdf->ezSetY($set_tlY);
        # Company details
        $smTxtSz = $set_txtSize - 3;
        $pdf->addText($set_tlX, $set_tlY, $smTxtSz, COMP_NAME);
        $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $smTxtSz, COMP_ADDRESS);
        $pdf->addText($set_tlX, $set_tlY - $smTxtSz * $nl, $smTxtSz, COMP_PADDR);
        # Company details cont
        $lrite = $set_pgXCenter + 60;
        $pdf->addText($lrite, $set_tlY - $smTxtSz, $smTxtSz, "COMPANY REG. " . COMP_REGNO);
        $pdf->addText($lrite, $set_tlY - $smTxtSz * 2, $smTxtSz, "TEL : " . COMP_TEL);
        $pdf->addText($lrite, $set_tlY - $smTxtSz * 3, $smTxtSz, "FAX : " . COMP_FAX);
        $pdf->addText($lrite, $set_tlY - $smTxtSz * 4, $smTxtSz, "VAT REG. " . COMP_VATNO);
        # Set y so its away from the company details
        $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 1));
        # customer details data
        $cusdet[] = array('tit' => "Account number : {$cust['accno']}");
        $cusdet[] = array('tit' => "{$cust['surname']}\n{$cust['addr1']}");
        $cusdet[] = array('tit' => "Balance Brought Forward : " . $curr . " {$balbf}");
        # customer details table
        $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 94));
        # just a new line
        $pdf->ezText("\n", $set_txtSize);
        # Statement table
        $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
        # just a new line
        $pdf->ezText("\n", $set_txtSize);
        # balance table data
        $baldat[] = array('tit' => "Total Outstanding Balance : " . $curr . " {$cust['balance']}");
        # balance table
        $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
        $i++;
    }
    # Send stream
    $pdf->ezStream();
    exit;
}
function alloc($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($rate, "float", 1, 10, "Invalid exchange rate.");
    if ($amt < 0.01) {
        $v->isOk($amt, "float", 5, 1, "Amount to small.");
    }
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $rate += 0;
    if ($rate == 0) {
        $rate = 1;
    }
    if ($bankid != 0) {
        # Get bank account name
        db_connect();
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $bankRslt = db_exec($sql);
        $bank = pg_fetch_array($bankRslt);
        if ($bank['btype'] == 'int') {
            // Retrieve the currency of the foreign bank account
            db_conn("cubit");
            $sql = "SELECT * FROM currency WHERE fcid='{$bank['fcid']}'";
            $rslt = db_exec($sql) or errDie("Unable to retrieve currency of the foreign bank account from Cubit.");
            $currs = pg_fetch_array($rslt);
            $bcur = $currs['symbol'];
            $amt = sprint($amt);
            $lamt = sprint($amt * $rate);
        } else {
            $lamt = sprint($amt);
            $amt = sprint($amt / $rate);
            $bcur = CUR;
        }
    } else {
        $bcur = CUR;
        $bank['accname'] = 'Cash';
        $bank['bankname'] = "";
        $lamt = sprint($amt);
        $amt = sprint($amt / $rate);
        $bcur = CUR;
    }
    # Customer name
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusid}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql);
    $cus = pg_fetch_array($cusRslt);
    $currs = getSymbol($cus['fcid']);
    $out = 0;
    $confirm = "\n\t\t\t<h3>New International Bank Receipt</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t\t<input type='hidden' name='rate' value='{$rate}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Field</th>\n\t\t\t\t\t<th>Value</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account</td>\n\t\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Received from</td>\n\t\t\t\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Description</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($descript) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Amount</td>\n\t\t\t\t\t<td valign='center'>{$cus['currency']} {$amt} | " . CUR . " {$lamt}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Exchange rate</td>\n\t\t\t\t\t<td valign='center'>" . CUR . " / {$cus['currency']} {$rate}</td>\n\t\t\t\t</tr>";
    if ($all == 0) {
        $out = $amt;
        // Connect to database
        db_connect();
        $sql = "SELECT invnum,invid,fbalance,terms,odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND fbalance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        $i = 0;
        while ($inv = pg_fetch_array($prnInvRslt) and $out > 0) {
            if ($i == 0) {
                $confirm .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'><br></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'><h3>Outstanding Invoices</h3></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<th>Invoice</th>\n\t\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t\t<th>Terms</th>\n\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t</tr>";
            }
            $invid = $inv['invid'];
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>{$cus['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>";
            if ($out >= $inv['fbalance']) {
                $val = $inv['fbalance'];
                $out = $out - $inv['fbalance'];
            } else {
                $val = $out;
                $out = 0;
            }
            $i++;
            $val = sprint($val);
            $confirm .= "<td><input type=hidden name='paidamt[{$invid}]' size=10 value='{$val}'>{$cus['currency']} {$val}</td></tr>";
        }
        $sql = "SELECT invnum,invid,fbalance,sdate as odate FROM nons_invoices WHERE cusid = '{$cusid}' AND done = 'y' AND fbalance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        while ($inv = pg_fetch_array($prnInvRslt) and $out > 0) {
            if ($i == 0) {
                $confirm .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'><br></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'><h3>Outstanding Invoices</h3></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<th>Invoice</th>\n\t\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t\t<th></th>\n\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t</tr>";
            }
            $invid = $inv['invid'];
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>{$cus['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>";
            if ($out >= $inv['fbalance']) {
                $val = $inv['fbalance'];
                $out = $out - $inv['fbalance'];
            } else {
                $val = $out;
                $out = 0;
            }
            $i++;
            $val = sprint($val);
            $confirm .= "\n\t\t\t\t\t\t<td><input type=hidden name='paidamt[{$invid}]' value='{$val}'><input type=hidden name=itype[{$invid}] value='Yes'>{$cus['currency']} {$val}</td>\n\t\t\t\t\t</tr>";
        }
        $out = sprint($out);
        if ($out > 0) {
            $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='5'><b>A general transaction will credit the client's account with {$cus['currency']} {$out} </b></td>\n\t\t\t\t\t</tr>";
        }
    }
    if ($all == 1) {
        $confirm .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<table " . TMMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Current</th>\n\t\t\t\t\t\t\t\t<th>30 days</th>\n\t\t\t\t\t\t\t\t<th>60 days</th>\n\t\t\t\t\t\t\t\t<th>90 days</th>\n\t\t\t\t\t\t\t\t<th>120 days</th>\n\t\t\t\t\t\t\t\t<th>Total Outstanding</th>\n\t\t\t\t\t\t\t</tr>";
        $curr = sprint(age($cusid, 29));
        $age30 = sprint(age($cusid, 59));
        $age60 = sprint(age($cusid, 89));
        $age90 = sprint(age($cusid, 119));
        $age120 = sprint(age($cusid, 149));
        # Customer total
        $custtot = $curr + $age30 + $age60 + $age90 + $age120;
        # Alternate bgcolor
        $confirm .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cus['currency']} {$curr}</td>\n\t\t\t\t\t<td>{$cus['currency']} {$age30}</td>\n\t\t\t\t\t<td>{$cus['currency']} {$age60}</td>\n\t\t\t\t\t<td>{$cus['currency']} {$age90}</td>\n\t\t\t\t\t<td>{$cus['currency']} {$age120}</td>\n\t\t\t\t\t<td>{$cus['currency']} {$custtot}</td>\n\t\t\t\t</tr>";
        $confirm .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='text' size='7' name='out1'></td>\n\t\t\t\t\t<td><input type='text' size='7' name='out2'></td>\n\t\t\t\t\t<td><input type='text' size='7' name='out3'></td>\n\t\t\t\t\t<td><input type='text' size='7' name='out4'></td>\n\t\t\t\t\t<td><input type='text' size='7' name='out5'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
        $confirm .= "\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
    }
    if ($all == 2) {
        // Connect to database
        db_connect();
        $sql = "SELECT invnum,invid,fbalance,terms,odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND fbalance>0 AND div = '" . USER_DIV . "'";
        $prnInvRslt = db_exec($sql);
        $tempi = pg_numrows($prnInvRslt);
        if (pg_numrows($prnInvRslt) < 1) {
            $sql = "SELECT invnum FROM nons_invoices WHERE cusid = '{$cusid}' AND done = 'y' AND fbalance>0 AND div = '" . USER_DIV . "'";
            $prnInvRslt = db_exec($sql);
            if (pg_numrows($prnInvRslt) < 1) {
                return "<li class='err'> There are no outstanding invoices for the selected debtor in Cubit.<br>\n\t\t\t\t\tTo make a payment in advance please select Auto Allocation";
            }
        } elseif ($tempi > 0) {
            $confirm .= "\n\t\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><h3>Outstanding Invoices</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th>Terms</th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
            $i = 0;
            // for bgcolor
            while ($inv = pg_fetch_array($prnInvRslt)) {
                $invid = $inv['invid'];
                $confirm .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>{$cus['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>";
                $val = '';
                if (pg_numrows($prnInvRslt) == 1) {
                    $val = $amt;
                }
                $confirm .= "\n\t\t\t\t\t\t\t<td><input type='text' name='paidamt[{$invid}]' size='10' value='{$val}'></td>\n\t\t\t\t\t\t</tr>";
            }
        }
        $sql = "SELECT invnum,invid,fbalance,sdate as odate FROM nons_invoices WHERE cusid = '{$cusid}' AND done = 'y' AND fbalance>0 AND div = '" . USER_DIV . "'";
        $prnInvRslt = db_exec($sql);
        if (pg_numrows($prnInvRslt) > 0) {
            $confirm .= "\n\t\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><h3>Outstanding Invoices</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th></th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
            $i = 0;
            // for bgcolor
            while ($inv = pg_fetch_array($prnInvRslt)) {
                $invid = $inv['invid'];
                $confirm .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>{$cus['currency']} {$inv['fbalance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>";
                $val = '';
                if (pg_numrows($prnInvRslt) == 1) {
                    $val = $amt;
                }
                $confirm .= "\n\t\t\t\t\t\t\t<td><input type='text' name='paidamt[{$invid}]' size='10' value='{$val}'><input type='hidden' name='itype[{$invid}]' value='YnYn'></td>\n\t\t\t\t\t\t</tr>";
            }
        }
    }
    $confirm .= "\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return view($acctype, $bankname, $loc, $branchname, $branchcode, $accname, $accnum, $details);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($acctype, "string", 1, 30, "Invalid Account Type.");
    $v->isOk($bankname, "string", 1, 50, "Invalid Bank name.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($branchname, "string", 1, 50, "Invalid Branch Name.");
    $v->isOk($branchcode, "string", 1, 15, "Invalid Branch Code.");
    $v->isOk($accname, "string", 1, 50, "Invalid Account Name.");
    $v->isOk($accnum, "num", 1, 20, "Invalid Account Number.");
    $v->isOk($glacc, "num", 1, 20, "Invalid Ledger account.");
    $v->isOk($details, "string", 1, 255, "Invalid Details.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $curr = getSymbol($fcid);
    # processes
    db_connect();
    # begin sql transaction
    # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # Register bank account
    $sql = "\n\t\tINSERT INTO bankacct (\n\t\t\tacctype, bankname, btype, fcid, currency, branchname, \n\t\t\tbranchcode, accname, accnum, details, div\n\t\t) VALUES (\n\t\t\t'{$acctype}', '{$bankname}', '{$loc}', '{$fcid}', '{$curr['name']}', '{$branchname}', \n\t\t\t'{$branchcode}', '{$accname}', '{$accnum}', '{$details}', '" . USER_DIV . "'\n\t\t)";
    $bankAccRslt = db_exec($sql) or errDie("Unable to add bank account to database.");
    # Get last id from bank accounts
    $accid = pglib_lastid("cubit.bankacct", "bankid");
    # Create hook
    core_connect();
    $hook = "INSERT INTO bankacc(accid, accnum, div) VALUES('{$accid}', '{$glacc}', '" . USER_DIV . "')";
    $Rlst = db_exec($hook) or errDie("Unable to add hiik for for new bank account", SELF);
    # Commit sql transaction
    # pglib_transaction ("COMMIT") or errDie("Unable to finish a database transaction.",SELF);
    # status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>New Bank Account added to database</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New Bank Account , {$accname}, was successfully added to Cubit.</td>\n\t\t\t</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 bgcolor='#88BBFF'>\n\t\t\t\t<td><a href='bankacct-new.php'>Add New Bank Account</a></td>\n\t\t\t</tr>\n\t\t\t<tr bgcolor='#88BBFF'>\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</tr>";
    return $write;
}
function printaccnt()
{
    // Set up table to display in
    $OUTPUT = "\n\t\t<center>\n\t\t<h3>View Bank Accounts</h3></td>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Account Type</th>\n\t\t\t\t<th>Bank Name</th>\n\t\t\t\t<th>Type</th>\n\t\t\t\t<th>Currency</th>\n\t\t\t\t<th>Branch Name</th>\n\t\t\t\t<th>Branch Code</th>\n\t\t\t\t<th>Account Name</th>\n\t\t\t\t<th>Account Number</th>\n\t\t\t\t<th>Foreign Balance</th>\n\t\t\t\t<th>Local Currency</th>\n\t\t\t\t<th>Details</th>\n\t\t\t\t<th colspan='2'>Options</th>\n\t\t\t</tr>";
    # Connect to database
    db_Connect();
    $sql = "SELECT * FROM bankacct WHERE div = '" . USER_DIV . "' ORDER BY bankname,branchname";
    $bankRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank account details from database.", SELF);
    $numrows = pg_numrows($bankRslt);
    if ($numrows < 1) {
        $OUTPUT = "No Bank Accounts.";
        require "../template.php";
    }
    # Locations drop down
    $locs = array("loc" => "Local", "int" => "International");
    # display all orders
    for ($i = 0; $i < $numrows; $i++) {
        $bankacc = pg_fetch_array($bankRslt, $i);
        if ($bankacc['fcid'] != 0) {
            $curr = getSymbol($bankacc['fcid']);
        } else {
            $curr = 0;
            $locs[$bankacc['btype']] = "Local";
        }
        $type = $locs[$bankacc['btype']];
        # Get hook account number
        core_connect();
        $sql = "SELECT * FROM bankacc WHERE accid = '{$bankacc['bankid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
        # Check if link exists
        if (pg_numrows($rslt) < 1) {
            return "<li class='err'>ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
        }
        $banklnk = pg_fetch_array($rslt);
        # Get bank balance
        $sql = "SELECT (debit - credit) as bal FROM core.trial_bal\n\t\t\t\tWHERE accid = '{$banklnk['accnum']}' AND period='12' AND div = '" . USER_DIV . "'";
        $brslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
        $bal = pg_fetch_array($brslt);
        $fbal = $bankacc['btype'] == 'int' ? "{$curr['symbol']} {$bankacc['fbalance']}" : "<center> - </center>";
        $lbal = $bankacc['btype'] == 'int' ? CUR . " {$bankacc['balance']}" : CUR . " " . sprint($bal['bal']);
        # alternate bgcolor
        $bgColor = bgcolorc($i);
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$bankacc['acctype']}</td>\n\t\t\t\t<td>{$bankacc['bankname']}</td>\n\t\t\t\t<td>{$type}</td>\n\t\t\t\t<td>{$curr['symbol']} - {$curr['name']}</td>\n\t\t\t\t<td>{$bankacc['branchname']}</td>\n\t\t\t\t<td>{$bankacc['branchcode']}</td>\n\t\t\t\t<td>{$bankacc['accname']}</td>\n\t\t\t\t<td align='right'>{$bankacc['accnum']}</td>\n\t\t\t\t<td align='right'>{$fbal}</td>\n\t\t\t\t<td align='right'>{$lbal}</td>\n\t\t\t\t<td>{$bankacc['details']}</td>";
        if ($bankacc['type'] == 'cr') {
            $OUTPUT .= "<td><a href='creditcard-edit.php?bankid={$bankacc['bankid']}'>Edit</a></td>";
        } elseif ($bankacc['type'] == 'ptrl') {
            $OUTPUT .= "<td><a href='petrolcard-edit.php?bankid={$bankacc['bankid']}'>Edit</a></td>";
        } else {
            $OUTPUT .= "<td><a href='bankacct-edit.php?bankid={$bankacc['bankid']}'>Edit</a></td>";
        }
        db_connect();
        # Check if record can be removed
        $sql = "SELECT * FROM cashbook WHERE banked = 'no' AND bankid='{$bankacc['bankid']}' AND div = '" . USER_DIV . "'";
        $rs = db_exec($sql) or errDie("Unable to get cashbook entries.", SELF);
        if (pg_numrows($rs) > 0) {
            $OUTPUT .= "<td><br></td></tr>";
        } else {
            $OUTPUT .= "<td><a href='bankacct-rem.php?bankid={$bankacc['bankid']}'>Delete</a></td></tr>";
        }
    }
    $OUTPUT .= "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\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>";
    require "../template.php";
}
function cwrite($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $td = $inv['sdate'];
    $currs = getSymbol($inv['fcid']);
    # Update xrate
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    xrate_update($inv['fcid'], $inv['xrate'], "invoices", "invid");
    xrate_update($inv['fcid'], $inv['xrate'], "custran", "id");
    db_connect();
    # cust
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    $cus = pg_fetch_array($custRslt);
    $details = "\n\t<tr><td>{$cus['surname']}</td></tr>\n\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\n\t<tr><td>{$cus['vatnum']}</td></tr>";
    $na = $cus['surname'];
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # 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);
    $refnum = getrefnum();
    /*refnum*/
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    $real_invid = divlastid('inv', USER_DIV);
    db_connect();
    # Put in product
    while ($stk = pg_fetch_array($stkdRslt)) {
        $stkacc = $stkaccs[$stk['id']];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        //print $inv['chrgvat'];exit;
        $t = $inv['chrgvat'];
        $VATP = $vd['vat_amount'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $VATP / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $VATP / 100);
                }
            }
        }
        $f = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $f + $va, $va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        $products .= "<tr valign=top><td>{$stk['description']}</td><td>{$stk['qty']}</td><td>{$inv['currency']}  {$stk['unitcost']}</td><td>{$inv['currency']} {$stk['amt']}</td></tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class=err>Department not Found.";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Customer and Credit stock
        writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt * $inv['xrate'], "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
    }
    # Debit bank and credit the account involved
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $LVAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
    $sdate = date("Y-m-d");
    db_connect();
    $sql = "UPDATE nons_invoices SET cusid = '{$cusnum}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount,  balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$LTOTAL}'::numeric(13,2)), fbalance = (fbalance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($cusnum, $dept['incacc'], $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $LTOTAL, "d");
    frecordDT($TOTAL, $cusnum, $inv['xrate'], $inv['fcid'], $inv['sdate']);
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$LVAT}', '{$LTOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$cusnum}','{$na}','Non-stock International Invoice {$real_invid}','{$inv['sdate']}','" . sprint($LTOTAL - $LVAT) . "','{$LVAT}','" . sprint($LTOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('dt', 'Sales', '{$td}', 'Non Stock Invoice No.{$real_invid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t<center>\n\t\t\t\t{$cc}\n\t\t\t\t<h2>Tax Invoice</h2>\n\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width='750'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\tVAT No. " . COMP_VATNO . "\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width='230' height='47'></td>\n\t\t\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$real_invid}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['docref']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['sdate']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$inv['remarks']}</td>\n\t\t\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t</table>\n\t\t\t\t</center>\n\t\t\t";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "num", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($o_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($o_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($o_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $o_year . "-" . $o_month . "-" . $o_day;
    if (!checkdate($o_month, $o_day, $o_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serai no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid  Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    db_connect();
    if (isset($printdel)) {
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('Delivery Note','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
        # currency
        $currs = getSymbol($inv['fcid']);
    } else {
        $cust = pg_fetch_array($custRslt);
        # If customer was just selected/changed, get the following
        if ($inv['cusnum'] != $cusnum) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
            $xrate = getRate($cust['fcid']);
        }
        # currency
        $currs = getSymbol($cust['fcid']);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
                // 				if(isset($remprod)){
                // 					if(in_array($keys, $remprod)){
                // 						# skip product (wonder if $keys still align)
                // 						$amt[$keys] = 0;
                // 						continue;
                // 					}else{
                // 						# get selamt from selected stock
                // 						$sql = "SELECT * FROM stock WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
                // 						$stkRslt = db_exec($sql);
                // 						$stk = pg_fetch_array($stkRslt);
                //
                // 						$t=$cunitcost[$keys];
                //
                // 						# Calculate the unitcost
                // 						if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
                // 							$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
                // 						}else{
                // 							$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
                // 						}
                //
                // 						# Calculate the Discount discount
                // 						if($disc[$keys] < 1){
                // 							if($discp[$keys] > 0){
                // 								$disc[$keys] = (($discp[$keys]/100) * $t);
                // 							}
                // 						}else{
                // 							$discp[$keys] = (($disc[$keys] * 100) / $t);
                // 						}
                //
                // 						# Calculate amount
                // 						$funitcost[$keys] = $unitcost[$keys];
                // 						$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys]));
                //
                // 						# Calculate amount
                // 						// $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                // 						$unitcost[$keys] = sprint($funitcost[$keys]/$xrate);
                // 						$amt[$keys] = sprint($famt[$keys]/$xrate-($disc[$keys]));
                //
                // 						$Sl="SELECT * FROM vatcodes WHERE id='$vatcodes[$keys]'";
                // 						$Ri=db_exec($Sl);
                //
                // 						if(pg_num_rows($Ri)<1) {
                // 							return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>");
                // 						}
                // 						$vd=pg_fetch_array($Ri);
                //
                // 						# Check Tax Excempt
                // 						if($stk['exvat'] == 'yes'||$vd['zero']=="Yes"){
                // 							$taxex += $amt[$keys];
                // 						}
                //
                // 						# insert invoice items
                // 						$sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, funitcost, amt, famt, disc, discp, serno, div,vatcode,del) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', '$funitcost[$keys]', '$amt[$keys]', '$famt[$keys]', '$disc[$keys]', '$discp[$keys]', '$sernos[$keys]', '".USER_DIV."','$vatcodes[$keys]','0')";
                // 						$rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.",SELF);
                //
                // 						if(strlen($stkt['serno']) > 0)
                // 							ext_resvSer($stkt['serno'], $stk['stkid']);
                //
                // 						# update stock(alloc + qty)
                // 						$sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
                // 						$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
                // 					}
            } else {
                # Get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                /*# Calculate the unitcost
                		if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
                			$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
                		}else{
                			$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
                		}*/
                $t = $cunitcost[$keys];
                # Calculate the unitcost
                if ($unitcost[$keys] > 0 && $cunitcost[$keys] == 0) {
                    $cunitcost[$keys] = $unitcost[$keys] / $xrate;
                } else {
                    $unitcost[$keys] = $cunitcost[$keys] * $xrate;
                }
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $t;
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $t;
                }
                if ($xrate < 1) {
                    $xrate = 1;
                }
                //$disc[$keys]=$disc[$keys]*$xrate;
                # Calculate amount
                $funitcost[$keys] = $unitcost[$keys];
                $famt[$keys] = $qtys[$keys] * $funitcost[$keys];
                //$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys] - $disc[$keys]));
                # Calculate amount
                // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                $unitcost[$keys] = sprint($funitcost[$keys] / $xrate);
                $amt[$keys] = sprint($famt[$keys] / $xrate - $disc[$keys]);
                //$amt[$keys] = sprint($famt[$keys]/$xrate);
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                }
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                }
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tfunitcost, amt, famt, disc, \n\t\t\t\t\t\t\tdiscp, serno, div, vatcode, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$funitcost[$keys]}', '{$amt[$keys]}', '{$famt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', \n\t\t\t\t\t\t\t'{$sernos[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', '0'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                if (strlen($sernos[$keys]) > 0) {
                    ext_resvSer($sernos[$keys], $stk['stkid']);
                }
                # update stock(alloc + qty)
                $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $FTOTAL = sprint($TOTAL * $xrate);
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', \n\t\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', docref = '{$docref}', \n\t\t\t\tterms = '{$terms}', salespn = '{$salespn}', fcid = '{$cust['fcid']}', currency = '{$currs['symbol']}', xrate = '{$xrate}', \n\t\t\t\todate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', \n\t\t\t\ttotal = '{$TOTAL}', balance = '{$FTOTAL}', fbalance = '{$TOTAL}', comm = '{$comm}', location = '{$cust['location']}', \n\t\t\t\tserd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (strlen($bar) > 0) {
        $Sl = "SELECT * FROM possets WHERE div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_numrows($Rs) < 1) {
            return details($_POST, "<a href='pos-set.php'>Please set the point of sale setting by clicking here.</a>");
        }
        $Dets = pg_fetch_array($Rs);
        if ($Dets['opt'] == "No") {
            switch (substr($bar, strlen($bar) - 1, 1)) {
                case "0":
                    $tab = "ss0";
                    break;
                case "1":
                    $tab = "ss1";
                    break;
                case "2":
                    $tab = "ss2";
                    break;
                case "3":
                    $tab = "ss3";
                    break;
                case "4":
                    $tab = "ss4";
                    break;
                case "5":
                    $tab = "ss5";
                    break;
                case "6":
                    $tab = "ss6";
                    break;
                case "7":
                    $tab = "ss7";
                    break;
                case "8":
                    $tab = "ss8";
                    break;
                case "9":
                    $tab = "ss9";
                    break;
                default:
                    return details($_POST, "The code you selected is invalid");
            }
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '" . USER_DIV . "', '0'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "UPDATE " . $tab . " SET active = 'no' WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\n\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0','{$bar}', '" . USER_DIV . "', '0'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # Check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.</li>";
            return details($_POST, $error);
        }
        # Insert quote to DB
        $sql = "UPDATE invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if ($data['value'] == "Yes") {
            # Print the invoice
            $OUTPUT = "<script>nhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>";
        } else {
            # Print the invoice
            $OUTPUT = "<script>printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>";
        }
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New International Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>International Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
}
function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sdate = $s_year . "-" . $s_month . "-" . $s_day;
    if (!checkdate($s_month, $s_day, $s_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        //		is_int fails if the value is 1 ??? ctype_digit seems to work better
        //		if (!is_int($qtys[$key])) {
        if (!ctype_digit($qtys[$key])) {
            $v->addError(0, "Invalid Item Quantity.");
        }
        if ($qtys[$key] > $oqtys[$key]) {
            $v->isOk("##", "num", 1, 1, "Error : Item quantity cannot be more than invoiced quantity.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm = "{$err}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return details($_POST, $err);
        return $confirm;
    }
    # 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);
    $currs = getSymbol($inv['fcid']);
    /* --- Start Products Display --- */
    # Products layout
    $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 width='5%'>#</th>\n\t\t\t\t\t\t\t<th width='40%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t<th width='25%'>ACCOUNT</th>\n\t\t\t\t\t\t<tr>";
    # get selected stock in this Invoice
    $any = false;
    $i = 0;
    $totamt = 0;
    foreach ($ids as $key => $id) {
        if ($qtys[$key] < 1) {
            continue;
        }
        $any = true;
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        $accRs = get("core", "accname,topacc,accnum", "accounts", "accid", $stkacc);
        $acc = pg_fetch_array($accRs);
        # Calculate amount
        $totamt += $amt[$key] = $qtys[$key] * $stkd['unitcost'];
        $any = true;
        $i++;
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'>{$i}<input type='hidden' name='ids[]' value='{$stkd['id']}'></td>\n\t\t\t\t<td>{$stkd['description']}</td>\n\t\t\t\t<td><input type='hidden' name='qtys[]' value='{$qtys[$key]}'>{$qtys[$key]}</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['unitcost']}</td>\n\t\t\t\t<td><input type='hidden' name='amts[]' value='{$amt[$key]}'>{$inv['currency']} {$amt[$key]}</td>\n\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t</tr>";
    }
    $products .= "</table>";
    # if there isn't any products
    if (!$any) {
        $err = "<li class='err'> Error : There are no products selected.</li>";
        return details($_POST, $err);
        return "<li class='err'> Error : There are no products selected.</li>";
    }
    /* --- Start Some calculations --- */
    //  commented: 2006-04-25
    // 	# calculate subtot
    // 	if( isset($amt) ){
    // 		$TOTAL = array_sum($amt);
    // 	}else{
    // 		$TOTAL = 0.00;
    // 	}
    //
    // 	# if vat is not included
    // 	$VATP = TAX_VAT;
    // 	if($inv['chrgvat'] == "yes"){
    // 		$SUBTOT = sprintf("%0.2f", $TOTAL * 100 / (100 + $VATP) );
    // 	} elseif($inv['chrgvat'] == "no") {
    // 		$SUBTOT = $TOTAL;
    // 		$TOTAL = sprintf("%0.2f", $TOTAL * (100 + $VATP) /100 );
    // 	}else{
    // 		$SUBTOT = $TOTAL;
    // 	}
    //
    // 	// compute the sub total (total - vat), done this way because the specified price already includes vat
    // 	$VAT = sprint($TOTAL - $SUBTOT);
    // inclusive
    $SUBTOT = sprint($totamt);
    if ($inv["chrgvat"] == "yes") {
        $VAT = $totamt - $totamt / (1 + TAX_VAT / 100);
    } else {
        $VAT = $SUBTOT * TAX / 100;
        $TOTAL = $SUBTOT + $VAT;
    }
    vsprint($VAT);
    vsprint($TOTAL);
    /* --- End Some calculations --- */
    # Format date
    // list($syear, $smon, $sday) = explode("-", $inv['sdate']);
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Non-Stock Credit Note</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='write'>\n\t\t\t\t\t\t<input type='hidden' name='invid' value={$invid}>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign=top>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Customer Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Customer Vat Number</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</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><th colspan='2'> Non-Stock Invoice Details </th></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 Invoice No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</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("s", $s_year, $s_month, $s_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>Foreign Currency</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$currs['symbol']} - {$currs['name']} &nbsp;&nbsp;Exchange rate " . CUR . " {$inv['xrate']}</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'>{$inv['chrgvat']}</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<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='40%'>Quick Links</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>Remarks</th>\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='15%'><br></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-invoice-new.php'>New Non-Stock Invoices</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'>" . nl2br($inv['remarks']) . "</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><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></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'><input type='hidden' name='subtot' value='{$SUBTOT}'>{$inv['currency']} {$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 @ " . TAX_VAT . " %</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'><input type='hidden' name='vat' value='{$VAT}'>{$inv['currency']} {$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'><input type='hidden' name='total' value='{$totamt}'>{$inv['currency']} {$totamt}</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 type='submit' value='Confirm &raquo'></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;
}
function write($_POST)
{
    # Connect to cubit
    db_connect();
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 4, "Invalid Bank Account ID.");
    $v->isOk($acctype, "string", 1, 30, "Invalid Account Type.");
    $v->isOk($bankname, "string", 1, 50, "Invalid Bank name.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($branchname, "string", 1, 50, "Invalid Branch Name.");
    $v->isOk($branchcode, "string", 1, 15, "Invalid Branch Code.");
    $v->isOk($accname, "string", 1, 50, "Invalid Account Name.");
    $v->isOk($accnum, "num", 1, 20, "Invalid Account Number.");
    $v->isOk($glacc, "num", 1, 20, "Invalid Ledger account.");
    $v->isOk($cardnum, "num", 16, 16, "Invalid Card Number.");
    $v->isOk($mon, "num", 1, 2, "Invalid Expiry date.");
    $v->isOk($year, "num", 4, 4, "Invalid Expiry date.");
    $v->isOk($lastdigits, "num", 3, 3, "Invalid Last Digits.");
    $v->isOk($cardtyp, "string", 1, 255, "Invalid Card Type.");
    $v->isOk($details, "string", 1, 255, "Invalid Details.");
    if ($cardtyp == 'other') {
        $v->isOk($cardname, "string", 1, 255, "Invalid Card Type.");
        $cardtyp = $cardname;
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $curr = getSymbol($fcid);
    db_connect();
    $sql = "UPDATE bankacct SET acctype = '{$acctype}', bankname = '{$bankname}', branchname = '{$branchname}', btype = '{$loc}', fcid = '{$fcid}', currency = '{$curr['name']}', branchcode='{$branchcode}', accname='{$accname}', accnum='{$accnum}', details='{$details}',\n\tcardnum = '{$cardnum}', mon = '{$mon}', year = '{$year}', digits = '{$lastdigits}', cardtype = '{$cardtyp}' WHERE bankid='{$bankid}' AND div = '" . USER_DIV . "'";
    $nwUsrRslt = db_exec($sql) or errDie("Unable to edit bank account.");
    # ReCreate hook
    core_connect();
    $hook = "UPDATE bankacc SET accnum = '{$glacc}' WHERE accid = '{$bankid}'";
    $Rlst = db_exec($hook) or errDie("Unable to add hook for for bank account", SELF);
    # Status report
    $write = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>Bank Account Edited</th></tr>\n\t\t<tr class=datacell><td>Bank Account <b>{$accname}</b>, was successfully edited.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t        <tr><th>Quick Links</th></tr>\n            <tr class='bg-odd'><td><a href='bankacct-view.php'>View Bank Accounts</a></td></tr>\n\t        <tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n\t</table>";
    return $write;
}
function write()
{
    extract($_POST);
    if (isset($back)) {
        return enter();
    }
    if ($err = validate($_POST)) {
        return enter($err);
    }
    /* check account number */
    if (!isset($cusnum)) {
        $qry = new dbSelect("customers", "cubit", grp(m("where", "accno='{$accno}' AND div='" . USER_DIV . "'")));
        $qry->run();
        if ($qry->num_rows() > 0) {
            return enter("<li class='err'>A Customer/Client with this account number already exists.</li>");
        }
    }
    $data = qryCategory($category);
    $catname = $data["category"];
    $data = qryClass($class);
    $classname = $data["classname"];
    $data = qryPricelist($pricelist);
    $plist = $data["listname"];
    $curr = getSymbol($fcid);
    $currency = $curr["symbol"];
    /* fix numerics */
    $traddisc += 0;
    $setdisc += 0;
    $pricelist += 0;
    $overdue += 0;
    $credterm += 0;
    $credlimit += 0;
    pglib_transaction("BEGIN");
    /* insert into database / update */
    $cols = grp(m("deptid", $deptid), m("accno", $accno), m("surname", $surname), m("title", $title), m("init", $init), m("location", $location), m("fcid", $fcid), m("currency", $currency), m("category", $category), m("class", $class), m("addr1", $addr1), m("paddr1", $paddr1), m("del_addr1", $del_addr1), m("vatnum", $vatnum), m("contname", $contname), m("bustel", $bustel), m("tel", $tel), m("cellno", $cellno), m("fax", $fax), m("email", $email), m("url", $url), m("traddisc", $traddisc), m("setdisc", $setdisc), m("pricelist", $pricelist), m("chrgint", $chrgint), m("overdue", $overdue), m("intrate", $intrate), m("chrgvat", "yes"), m("credterm", $credterm), m("odate", $odate), m("credlimit", $credlimit), m("blocked", "no"), m("deptname", $deptname), m("classname", $classname), m("catname", $catname), m("lead_source", $lead_source), m("comments", $comments), m("sales_rep", $sales_rep), m("div", USER_DIV), m("bankname", $bankname), m("branname", $branname), m("brancode", $brancode), m("bankaccname", $bankaccname), m("bankaccno", $bankaccno), m("bankacctype", $bankacctype), m("team_id", $team_id), m("registration", $registration));
    $where = wgrp(m("cusnum", isset($cusnum) ? $cusnum : 0));
    $qryi = new dbUpdate("customers", "cubit", $cols, $where);
    $qryi->run(DB_REPLACE);
    /* get id */
    if (!isset($cusnum)) {
        $cusnum = pglib_lastid("customers", "cusnum");
        $newcust = true;
        // used later to check if we should create the ledgers
    }
    /* add to/update contact list */
    $cols = grp(m("surname", $surname), m("title", $title), m("ref", "Customer"), m("tell", $tel), m("tell_office", $bustel), m("cell", $cellno), m("fax", $fax), m("email", $email), m("hadd", $addr1), m("padd", $paddr1), m("del_addr", $del_addr1), m("date", $odate), m("cust_id", $cusnum), m("con", "No"), m("lead_source", $lead_source), m("description", $comments), m("account_type", "Customer"), m("accountname", $surname), m("account_id", $cusnum), m("by", USER_NAME), m("div", USER_DIV));
    $where = wgrp(m("cust_id", $cusnum));
    $qryi->setTable("cons", "cubit");
    $qryi->setOpt($cols, $where);
    $qryi->run(DB_REPLACE);
    if (PRD_STATE == "py") {
        $audit_db = YR_NAME . "_audit";
        $actyear = PYR_NAME;
    } else {
        $audit_db = "audit";
        $actyear = YR_NAME;
    }
    if (isset($newcust)) {
        /* create customer ledgers */
        for ($i = 1; $i <= 12; ++$i) {
            /* period customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV));
            $qryi->setTable("custledger", "{$i}");
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
            /* audit customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV), m("actyear", $actyear));
            $qryi->setTable(getMonthName($i) . "_custledger", $audit_db);
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
        }
        if (isset($crm)) {
            header("Location: crm/tokens-new.php?value={$surname}");
            exit;
        }
        if ($re != "not") {
            $qryi->setTable("invoices", "cubit");
            $cols = grp(m("cusnum", $cusnum));
            $where = wgrp(m("invid", $re));
            $qryi->setOpt($cols, $where);
            $qryi->run(DB_UPDATE);
            header("Location: cust-credit-stockinv.php?invid={$re}&cont=1&letters=");
            exit;
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to add customer to database. (TC)");
    // Update documents
    $sql = "SELECT * FROM crm.ctmp_docs WHERE session='{$_REQUEST['CUBIT_SESSION']}'";
    $ctdoc_rslt = db_exec($sql) or errDie("Unable to retrieve docs.");
    while ($ctdoc_data = pg_fetch_array($ctdoc_rslt)) {
        $sql = "INSERT INTO crm.customer_docs (cusnum, file, type, filename, size)\n\t\tVALUES ('{$cusnum}', '{$ctdoc_data['file']}', '{$ctdoc_data['type']}',\n\t\t\t\t'{$ctdoc_data['filename']}', '{$ctdoc_data['size']}')";
        db_exec($sql) or errDie("Unable to save files to customer.");
        $sql = "DELETE FROM crm.ctmp_docs WHERE id='{$ctdoc_data['id']}'";
        db_exec($sql) or errDie("Unable to remove tmp file.");
    }
    $sql = "SELECT * FROM cubit.cons WHERE cust_id='{$cusnum}'";
    $con_rslt = db_exec($sql) or errDie("Unable to retrieve contact.");
    $con_data = pg_fetch_array($con_rslt);
    if (pg_num_rows($con_rslt)) {
        $con_out = "\n\t\t<a href='javascript:popupOpen(\"groupware/conper-add.php?type=conn&id={$con_data['id']}\")'>\n\t\t\tAdd Sub Contact\n\t\t</a>";
    } else {
        $con_out = "";
    }
    onthespot_declare();
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Customer add/update successful.</th>\n\t</tr>\n\t<tr class='datacell'>\n\t\t<td>\n\t\t\tNew Customer <b>{$surname}</b>,\n\t\t\thas been successfully added to the system.\n\t\t\t{$con_out}</td>\n\t</tr>\n\t</table>";
    $OUT .= onthespot_out(mkQuickLinks(ql("customers-new.php", "Add Customers"), ql("customers-view.php", "View Customers")));
    return $OUT;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 9, "Invalid Order ID");
    $v->isOk($ordernum, "string", 0, 20, "Invalid order number.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier number.");
    $v->isOk($terms, "num", 1, 5, "Invalid terms days.");
    $v->isOk($npuri_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($npuri_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($npuri_year, "num", 1, 5, "Invalid Date year.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $v->isOk($xrate, "float", 1, 20, "Invalid Exchange Rate.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $pdate = $npuri_year . "-" . $npuri_month . "-" . $npuri_day;
    if (!checkdate($npuri_month, $npuri_day, $npuri_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $ddate = $del_year . "-" . $del_month . "-" . $del_day;
    if (!checkdate($del_month, $del_day, $del_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($des[$keys], "string", 1, 255, "Invalid Description.");
            $v->isOk($cod[$keys], "string", 0, 255, "Invalid Item Code.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # 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>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier  info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier  information");
    $sup = pg_fetch_array($supRslt);
    # Currency
    $currs = getSymbol($sup['fcid']);
    $curr = $currs['symbol'];
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$pur['purnum']}</b> has already been received.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $shipchrg += 0;
    $tax += 0;
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    $VATP = TAX_VAT;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate the unitcost
                    if ($cunitcost[$keys] > 0) {
                        $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                    } else {
                        $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                    }
                    # Calculate the duty amount
                    if ($duty[$keys] < 1) {
                        if ($dutyp[$keys] > 0) {
                            $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                        }
                    } else {
                        if ($unitcost[$keys] > 0) {
                            $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                        } else {
                            $dutyp[$keys] = 0;
                        }
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                    # insert Order items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', '{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
            } else {
                # Calculate the unitcost
                if ($cunitcost[$keys] > 0) {
                    $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                } else {
                    $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                }
                # Calculate the duty amount
                if ($duty[$keys] < 1) {
                    if ($dutyp[$keys] > 0) {
                        $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                    }
                } else {
                    if ($unitcost[$keys] > 0) {
                        $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                    } else {
                        $dutyp[$keys] = 0;
                    }
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                # insert Order items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, \n\t\t\t\t\t\tduty, dutyp, amt, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', \n\t\t\t\t\t\t'{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input name='recv' type='submit' value='Receive'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # Calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # shipchrg is in for curr
    $fshipchrg = $shipchrg;
    // $shipchrg = ($shipchrg * $xrate);
    # total
    $TOTAL = sprint($SUBTOT + $shipchrg + $tax);
    # total Duty
    if (isset($duty)) {
        $dutytot = sprint(array_sum($duty));
    } else {
        $dutytot = "0.00";
    }
    # Local Totals
    $LTOTAL = sprint($TOTAL * $xrate);
    $LSUBTOT = sprint($SUBTOT * $xrate);
    /* --- End Clac --- */
    # insert Order to DB
    $sql = "\n\t\tUPDATE nons_purch_int \n\t\tSET supid = '{$supid}',cusid = '{$delvat}', supplier = '{$sup['supname']}', supaddr = '{$sup['supaddr']}', terms = '{$terms}', \n\t\t\tpdate = '{$pdate}', ddate = '{$ddate}', fcid = '{$sup['fcid']}', currency = '{$curr}', curr = '{$curr}', tax = '{$tax}', \n\t\t\txrate = '{$xrate}', fshipchrg = '{$fshipchrg}', shipchrg = '{$shipchrg}', duty = '{$dutytot}', subtot = '{$SUBTOT}', \n\t\t\ttotal = '{$TOTAL}', balance = '{$TOTAL}', fsubtot = '{$LSUBTOT}', fbalance = '{$LTOTAL}', remarks = '{$remarks}' \n\t\tWHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $lastid = pglib_lastid("nons_purch_int", "purid");
    if (isset($donePrnt)) {
        $sql = "UPDATE nons_purch_int SET done='y' WHERE purid='{$purid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-purch-int-print.php?purid={$lastid}');\n\t\t\t\tmove('nons-purch-int-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($recv)) {
        header("Location: nons-purch-int-recv.php?purid={$purid}");
        exit;
    } elseif (!isset($doneBtn)) {
        return details($_POST);
    } else {
        # insert Order to DB
        $sql = "UPDATE nons_purch_int SET done = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New International Non-Stock Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>International Non-Stock Order from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a href='nons-purch-int-print.php?purid={$lastid}'>Print Order</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-purch-int-view.php'>View International Non-Stock Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    # Connect to cubit
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return editAccnt($bankid);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 4, "Invalid Bank Account ID.");
    $v->isOk($acctype, "string", 1, 30, "Invalid Account Type.");
    $v->isOk($bankname, "string", 1, 50, "Invalid Bank name.");
    $v->isOk($fcid, "num", 1, 30, "Invalid Currency.");
    $v->isOk($branchname, "string", 1, 50, "Invalid Branch Name.");
    $v->isOk($branchcode, "string", 1, 15, "Invalid Branch Code.");
    $v->isOk($accname, "string", 1, 50, "Invalid Account Name.");
    $v->isOk($accnum, "num", 1, 20, "Invalid Account Number.");
    $v->isOk($glacc, "num", 1, 20, "Invalid Ledger account.");
    $v->isOk($details, "string", 1, 255, "Invalid Details.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $curr = getSymbol($fcid);
    db_connect();
    $sql = "UPDATE bankacct SET acctype = '{$acctype}', bankname = '{$bankname}', btype = '{$loc}', fcid = '{$fcid}', currency = '{$curr['name']}', branchname='{$branchname}', branchcode='{$branchcode}', accname='{$accname}', accnum='{$accnum}', details='{$details}' WHERE bankid='{$bankid}' AND div = '" . USER_DIV . "'";
    $nwUsrRslt = db_exec($sql) or errDie("Unable to edit bank account.");
    # ReCreate hook
    core_connect();
    $hook = "UPDATE bankacc SET accnum = '{$glacc}' WHERE accid = '{$bankid}'";
    $Rlst = db_exec($hook) or errDie("Unable to add hook for for bank account", SELF);
    # Status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Account Edited</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Bank Account <b>{$accname}</b>, was successfully edited.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='bankacct-view.php'>View Bank Accounts</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 $write;
}
function confirm($_POST)
{
    # get vars
    extract($_POST);
    $prd += 0;
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Order number.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Orderd");
            }
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        $error = "";
        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 details($_POST, $error);
        return $confirm;
    }
    # get Order info
    db_conn($prd);
    $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);
    # currency
    $currs = getSymbol($pur['fcid']);
    $curr = $currs['symbol'];
    $currsel = "{$currs['symbol']} - {$currs['descrip']}";
    # 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 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;
    }
    $sup = pg_fetch_array($supRslt);
    /* --- Start Drop Downs --- */
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    list($dyear, $dmon, $dday) = explode("-", $pur['ddate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Products layout
    $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>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t<th colspan='2'>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th colspan='2'>DUTY</th>\n\t\t\t\t\t\t\t<th>LINE TOTAL</th>\n\t\t\t\t\t\t\t<th>COST PER UNIT</th>\n\t\t\t\t\t\t\t<th>ITEM ACCOUNT</th>\n\t\t\t\t\t\t<tr>";
    $amt = 0;
    foreach ($qtys as $keys => $value) {
        if ($qtys[$keys] < 1) {
            continue;
        }
        db_conn($prd);
        # Get selected stock line
        $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        core_connect();
        # Get selected stock line
        $sql = "SELECT accname,accid,topacc,accnum FROM accounts WHERE accid = '{$stkacc[$keys]}' AND div = '" . USER_DIV . "'";
        $accRslt = db_exec($sql);
        $acc = pg_fetch_array($accRslt);
        /* -- 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']);
        $amt = sprint($amt + $unitamt);
        /* -- End Calculations --*/
        # put in product
        $products .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='ids[]' value='{$stkd['id']}'>{$stkd['cod']}</td>\n\t\t\t\t\t\t\t\t<td>{$stkd['des']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t\t\t\t<td nowrap>{$pur['curr']} {$stkd['cunitcost']} or </td>\n\t\t\t\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t\t<td>{$pur['curr']} {$stkd['duty']} or </td>\n\t\t\t\t\t\t\t\t<td>{$stkd['dutyp']}%</td>\n\t\t\t\t\t\t\t\t<td nowrap>{$pur['curr']} {$stkd['amt']}</td>\n\t\t\t\t\t\t\t\t<td nowrap><input type='hidden' name='unitamts[]' value='{$unitamt}'>{$pur['curr']} {$unitamt}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='stkacc[]' value='{$acc['accid']}'>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* -- Final Layout -- */
    $confirm = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Return International Non-Stock Order</h3>\n\t\t\t\t\t<h2>Confirm Entry</h2>\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='prd' value='{$prd}'>\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>Account</td>\n\t\t\t\t\t\t\t\t\t\t<td>{$sup['supno']}</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>Supplier</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$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>Supplier Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><pre>{$pur['supaddr']}</pre></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 Order 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>Non-Stock Order 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<input type='hidden' name='refno' size='10' value='{$pur['refno']}'>\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'>{$pur['terms']} 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'>{$pday}-{$pmon}-{$pyear}</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>Foreign Currency</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$currsel} &nbsp;&nbsp;Exchange rate {$pur['curr']} {$pur['xrate']}</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>Tax</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} {$pur['tax']}</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>Shipping Charges</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['curr']} {$pur['shipchrg']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='dday' maxlength='2' value='{$dday}'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='dmon' maxlength='2' value='{$dmon}'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='dyear' maxlength='4' value='{$dyear}'>\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%'></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-purch-int-new.php'>New International Non-Stock Order</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'>" . nl2br($pur['remarks']) . "</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><a href='nons-purch-int-view.php'>View International Non-Stock Orders</a></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=100%>\n\t\t\t\t\t\t\t\t\t<!--<tr class='" . bg_class() . "'><\n\t\t\t\t\t\t\t\t\t\tth>TOTAL COST RECEIVED</th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$pur['curr']} {$amt}</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 type='submit' name='upBtn' value='Write'></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 $confirm;
}
/**
 * @ignore
 */
function fintInvoice($cusnum, $total, $rate)
{
    $ftotal = sprint($total * $rate);
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    $cus = pg_fetch_array($custRslt);
    $curr = getSymbol($cus['fcid']);
    $xrate = getRate($cus['fcid']);
    # Default data
    $sdate = date("Y-m-d");
    $invnum = divlastid('inv', USER_DIV);
    db_connect();
    # Insert purchase to DB
    $sql = "\n\t\tINSERT INTO nons_invoices (\n\t\t\tcusid, cusname, cusaddr, cusvatno, chrgvat, \n\t\t\tfcid, currency, xrate, sdate, subtot, \n\t\t\tbalance, fbalance, vat, total, done, \n\t\t\tusername, prd, invnum, typ, ctyp, \n\t\t\ttval, location, descrip, div, odate\n\t\t) VALUES (\n\t\t\t'{$cus['cusnum']}', '{$cus['cusname']} {$cus['surname']}', '{$cus['addr1']}', '{$cus['vatnum']}', 'none', \n\t\t\t'{$cus['fcid']}', '{$curr['symbol']}', '{$xrate}', '{$sdate}', '{$total}', \n\t\t\t'{$ftotal}', '{$total}', 0, '{$total}', 'y', \n\t\t\t'" . USER_NAME . "', '" . PRD_DB . "', '{$invnum}', 'inv', 's', \n\t\t\t'{$cusnum}', 'int', 'Interest Charged', '" . USER_DIV . "', '{$sdate}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create Interest Invoice.", SELF);
    # Get next ordnum
    $invid = lastinvid();
    # Insert purchase items
    $sql = "\n\t\tINSERT INTO nons_inv_items (\n\t\t\tinvid, qty, amt, cunitcost, unitcost, \n\t\t\tdescription, div\n\t\t) VALUES (\n\t\t\t'{$invid}', '1', '{$total}', '{$ftotal}', '{$total}', \n\t\t\t'Interest on Outstanding Invoices.', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    return $invnum;
}