function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select customer
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($custRslt) < 1) {
        return "<li> Invalid Customer ID.</li>";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    cus_xrate_update($cust['fcid'], $rate);
    xrate_update($cust['fcid'], $rate, "invoices", "invid");
    xrate_update($cust['fcid'], $rate, "custran", "id");
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t</tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordCT($samount, $cust['cusnum']);
        frecordCT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordDT($samount, $cust['cusnum']);
        frecordDT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$sfamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $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 + '{$samount}'), fbalance = (fbalance + '{$sfamt}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
    // Start layout
    $write = "\n\t\t\t<h3>Journal transaction has been recorded</h3>\n\t\t\t<table " . TMPL_tblDflts . " width='500'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t{$tran}\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr colspan='2'>\n\t\t\t\t\t<td><h4>Amount</h4></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>" . CUR . " {$famt}</b></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='25%'>\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 align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='../customers-view.php'>View Customers</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 calcPerc($type)
{
    core_connect();
    $intacc = gethook("accnum", "salesacc", "name", "SalesInt");
    db_connect();
    # Get all client that must be charged interest
    $sql = "SELECT surname, cusnum, balance, fbalance, deptid, intrate, location, fcid FROM customers WHERE chrgint = 'yes' AND (balance > 0 OR fbalance > 0) AND div = '" . USER_DIV . "'";
    $rs = db_exec($sql) or errDie("Unable to get clients from Cubit.");
    if (pg_numrows($rs) < 1) {
        # Return if they are not charging any interest
        return;
    }
    #go through matching customers ...
    while ($clnt = pg_fetch_array($rs)) {
        if ($clnt['location'] != 'int') {
            #local customer ...
            #figure out the percentage ... based on setting ...
            if ($type == 'brac') {
                # Get from bracket
                $sql = "SELECT percentage as perc FROM intbracs WHERE min <= '{$clnt['balance']}' AND max >= '{$clnt['balance']}'";
                $bRs = db_exec($sql);
                if (pg_numrows($bRs) > 0) {
                    $brac = pg_fetch_array($bRs);
                    $perc = $brac['perc'];
                } else {
                    $perc = 0;
                }
            } elseif ($type[0] == 'r') {
                $perc = $clnt['intrate'];
            } else {
                $perc = $type;
            }
            //calculate the amount to charge interest on ...
            $overdue = getOverdue($clnt['cusnum']);
            # Get Perc of overdue
            $pamt = sprint($perc / 12 / 100 * $overdue);
            $totamt = $pamt + $clnt['balance'];
            $ret[$clnt['cusnum']] = $totamt;
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$clnt['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            if ($pamt > 0) {
                $sdate = date("Y-m-d");
                $invnum = intInvoice($clnt['cusnum'], $pamt, $intacc);
                db_connect();
                # Record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}', '{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "', '{$sdate}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}', '{$pamt}','{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $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 + '{$pamt}'::numeric(13,2)) WHERE cusnum = '{$clnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                # Make ledge record
                custledger($clnt['cusnum'], $intacc, $sdate, 0, "Interest on Outstanding balance", $pamt, "d");
                # Write transaction  (debit debtors control, credit contra account)
                $refnum = getrefnum();
                writetrans($dept['debtacc'], $intacc, date("d-m-Y"), $refnum, $pamt, "Interest Received from customer : {$clnt['surname']}.");
                recordDT($pamt, $clnt['cusnum']);
            }
        } else {
            if ($type == 'brac') {
                # Get from bracket
                $sql = "SELECT percentage as perc FROM intbracs WHERE min <= '{$clnt['balance']}' AND max >= '{$clnt['balance']}'";
                $bRs = db_exec($sql);
                if (pg_numrows($bRs) > 0) {
                    $brac = pg_fetch_array($bRs);
                    $perc = $brac['perc'];
                } else {
                    $perc = 0;
                }
            } elseif ($type[0] == 'r') {
                $perc = $clnt['intrate'];
            } else {
                $perc = $type;
            }
            //		$overdue = getfOverdue($clnt['cusnum']);
            $overdue = getOverdue($clnt['cusnum']);
            $rate = sprint($clnt['balance'] / $clnt['fbalance']);
            # Get Perc of overdue
            $pamt = sprint($perc / 12 / 100 * $overdue);
            $totamt = $pamt + $clnt['fbalance'];
            $ret[$clnt['cusnum']] = $totamt;
            if ($rate == 0) {
                $rate = 1;
            }
            $ltotamt = sprint($totamt * $rate);
            $lpamt = sprint($ltotamt - $clnt['balance']);
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$clnt['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            if ($pamt > 0) {
                $sdate = date("Y-m-d");
                $invnum = fintInvoice($clnt['cusnum'], $pamt, $rate);
                db_connect();
                # Record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$clnt['cusnum']}', '{$invnum}', '{$pamt}','{$sdate}', \n\t\t\t\t\t\t'Interest on Outstanding balance', '" . USER_DIV . "', '{$sdate}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET fbalance = (fbalance + '{$pamt}'::numeric(13,2)), balance = '{$ltotamt}'::numeric(13,2) WHERE cusnum = '{$clnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                # Make ledge record
                custledger($clnt['cusnum'], $intacc, $sdate, 0, "Interest on Outstanding balance", $lpamt, "d");
                # Write transaction  (debit debtors control, credit contra account)
                $refnum = getrefnum();
                writetrans($dept['debtacc'], $intacc, date("d-m-Y"), $refnum, $lpamt, "Interest Received from customer : {$clnt['surname']}.");
                frecordDT($pamt, $lpamt, $clnt['cusnum'], $clnt['fcid']);
            }
        }
    }
    return $ret;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class=err>" . $e["msg"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $td = $date;
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($suppRslt) < 1) {
        return "<li> Invalid Supplier ID.";
    } else {
        $supp = pg_fetch_array($suppRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class=err>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    # update all supplies xchange rate first
    xrate_update($supp['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($supp['fcid'], $rate);
    $supp['supname'] = remval($supp['supname']);
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['credacc'], $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td><td>{$supp['supno']} - {$supp['supname']}</td></tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordCT(-$amount, $supp['supid']);
        frecordCT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$supp['supno']} - {$supp['supname']}</td><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td></tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordDT($amount, $supp['supid']);
        frecordDT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $edate = date("Y-m-d");
    # record the payment on the statement
    $sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$supp['supid']}', '{$td}', '0', '{$accid}', '{$details}', '{$sfamt}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$samount}'),fbalance = (fbalance + '{$sfamt}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Ledger Records
    suppledger($supp['supid'], $accid, $td, $refnum, $details, $amount, $type);
    db_connect();
    // Start layout
    $write = "<h3>Journal transaction has been recorded</h3>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n\t\t{$tran}\n\t\t<tr><td><br></td></tr>\n\t\t<tr colspan=2><td><h4>Amount</h4></td></tr>\n\t\t<tr class='bg-even'><td colspan=2><b>" . CUR . " {$famt}</b></td></tr>\n\t</table>\n\t<P>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../supp-view.php'>View Suppliers</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function 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";
}