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 write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $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($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # 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;
    }
    # 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) {
        $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
        $Rg = db_exec($Sl);
        if (pg_num_rows($Rg) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but its not there now, you must have deleted it, if you want to use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $add = pg_fetch_array($Rg);
        $bank['accnum'] = $add['accid'];
    } else {
        $bank = pg_fetch_array($rslt);
    }
    db_connect();
    # Customer name
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusid}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql);
    $cus = pg_fetch_array($cusRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    cus_xrate_update($cus['fcid'], $rate);
    xrate_update($cus['fcid'], $rate, "invoices", "invid");
    xrate_update($cus['fcid'], $rate, "custran", "id");
    bank_xrate_update($cus['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = date("Y-m-d");
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $famounts = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    db_connect();
    if ($all == 0) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)),fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            frecordCT($out, $cus['cusnum'], $rate, $cus['fcid']);
            $Sl = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cus['cusnum']}','0','" . $out * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out * $rate, "c");
            db_connect();
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out1 + $out2 + $out3 + $out4 + $out5 > 0) {
            $Sl = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','0','" . ($out1 + $out2 + $out3 + $out4 + $out5) * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", ($out1 + $out2 + $out3 + $out4 + $out5) * $rate, "c");
            db_connect();
        }
        if ($out1 > 0) {
            frecordCT($out1, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out2 > 0) {
            frecordCT($out2, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out3 > 0) {
            frecordCT($out3, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out4 > 0) {
            frecordCT($out4, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out5 > 0) {
            frecordCT($out5, $cus['cusnum'], $rate, $cus['fcid']);
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 2) {
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # Debtors
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
            if (!isset($itype[$ii])) {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                db_connect();
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            } else {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                db_connect();
                frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$famounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    /* start moving invoices */
    # move invoices that are fully paid
    $sql = "SELECT * FROM invoices WHERE fbalance = 0 AND balance = 0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        if ($invb['prd'] == 0) {
            $invb['prd'] = PRD_DB;
        }
        db_conn($invb['prd']);
        # Insert invoice to period DB
        $sql = "INSERT INTO invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, fcid, currency, xrate, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, fbalance, location, age, comm, discount, delivery, printed, done, div)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['fcid']}', '{$invb['currency']}', '{$invb['xrate']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '0', '{$invb['location']}', '{$invb['age']}', '{$invb['comm']}', '{$invb['discount']}', '{$invb['delivery']}', 'y', 'y', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            # insert invoice items
            $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM invoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    /* end moving invoices */
    # status report
    $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr><th>Bank Receipt</th></tr>\n\t\t\t\t<tr class='datacell'><td>Bank Receipt added to cash book.</td></tr>\n\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width=50%>{$write}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-inv.php'>Add Customer Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='cashbook-view.php'>View Cash Book</a></td></tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
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($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $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 "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= 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>";
    }
    $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 <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # 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;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    # Begin Updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # 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);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        $sp = "";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $stkd['amt'];
            $ex = "#";
        } else {
            $ex = "";
        }
        # all must be excempted
        if ($inv['chrgvat'] == 'nov') {
            $ex = "#";
        }
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'];
        # Insert stock record
        $sdate = date("Y-m-d");
        $csprice = sprint($stk['csprice'] * $stkd['qty']);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = sprint($stkd['famt']);
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
            $amtexvat = sprint($stkd['famt'] * 100 / (100 + $VATP));
        }
        db_connect();
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, \n\t\t\t\tdetails, div\n\t\t\t) VALUES (\n\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$amtexvat}', '{$csprice}', \n\t\t\t\t'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        # Sales rep commission
        $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        # Put in product
        $products .= "\n\t\t\t<tr valign='top'>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t<td>{$inv['currency']} " . sprint($stkd['unitcost']) . "</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['disc']}</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['amt']}</td>\n\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    $FSUBTOT = sprint($inv['subtot'] * $inv['xrate']);
    $FVAT = sprint($inv['vat'] * $inv['xrate']);
    $FTOTAL = sprint($inv['total'] * $inv['xrate']);
    $fdelchrg = sprint($inv['delchrg'] * $inv['xrate']);
    $ftraddiscm = sprint($inv['discount'] * $inv['xrate']);
    com_invoice($inv['salespn'], $FTOTAL, $commision * $inv['xrate'], $invnum, $td);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "int");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*$refnum*/
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' 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\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}','{$invnum}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO open_stmnt (\n\t\t\tcusnum, invid, amount, balance, date, type, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$TOTAL}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\tINSERT INTO inv_discs (\n\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, div, \n\t\t\ttotal\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$ftraddiscm}', '{$disc}', '{$inv['odate']}', '{$fdelchrg}', '" . USER_DIV . "', \n\t\t\t({$FSUBTOT}+{$fdelchrg})\n\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 + '{$FTOTAL}'), fbalance = (fbalance + '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $invnum, "Invoice No. {$invnum}", $FTOTAL, "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # cost amount
        $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
        # update stock(alloc - qty)
        $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        if ($stk['serd'] == 'yes') {
            ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
        }
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # dt(cos) ct(stock)
        writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        $tcosamt += $cosamt;
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $iamount = $iamount * $inv['xrate'];
    $ivat = $ivat * $inv['xrate'];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $FVAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $sql = "\n\t\tINSERT INTO salesrec (\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t) VALUES (\n\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'stk', '" . USER_DIV . "'\n\t\t)";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "\n\t\tINSERT INTO sj (\n\t\t\tcid, name, des, date, exl, vat, inc, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'International Invoice {$invnum}', '{$inv['odate']}', '" . sprint($FTOTAL - $FVAT) . "', \n\t\t\t'{$FVAT}', '" . sprint($FTOTAL) . "', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "0% VAT indicator";
        $expl = "VAT Exempt indicator";
    }
    # Avoid little box, <table border=1> <-- ehhhemm !!
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($FTOTAL - $FVAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t{$cc}\n\t\t<h2>Tax Invoice</h2>\n\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' width='30%'>\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<td>{$inv['surname']}</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>" . nl2br($inv['cusaddr']) . "</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>(VAT No. {$inv['cusvatno']})</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' width='30%'>\n\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_PADDR . "<br>\n\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\tVAT No. " . COMP_VATNO . "<br>\n\t\t\t\t</td>\n\t\t\t\t<td width='20%'>\n\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t</td>\n\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$invnum}</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>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t<td>{$inv['docref']}</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>Order No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</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>Terms</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</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>VAT</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</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='4'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>ITEM NUMBER</b></td>\n\t\t\t\t\t\t\t<td width='45%'><b>DESCRIPTION</b></td>\n\t\t\t\t\t\t\t<td><b>QTY</b></td>\n\t\t\t\t\t\t\t<td><b>UNIT PRICE</b></td>\n\t\t\t\t\t\t\t<td><b>DISCOUNT</b></td>\n\t\t\t\t\t\t\t<td><b>AMOUNT</b></td>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t{$products}\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>{$inv['comm']}</td>\n\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</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>Trade Discount</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['discount']}</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>Delivery Charge</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['delivery']}</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>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</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>GRAND TOTAL<b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$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><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$expl} = #</td>\n\t\t\t\t\t\t</tr>\n\t\t\t        </table>\n\t\t\t\t</td>\n\t\t\t\t<td><br></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function write($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = mkdate($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.");
        //		if (!is_int($qtys[$key])) {
        if (!ctype_digit($qtys[$key])) {
            $v->addError(0, "Invalid Item Quantity.");
        }
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $err .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $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 "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # 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();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    db_connect();
    /* --- Start Products Display --- */
    $td = $sndate;
    # Products layout
    $products = "";
    foreach ($ids as $key => $id) {
        $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'];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
        // 		}
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        $f = -vats($amts[$key], $inv['chrgvat']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", $f - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        $products .= "\n\t\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t\t<td>{$stkd['description']}</td>\n\t\t\t\t\t\t\t<td>{$qtys[$key]}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$amts[$key]}</td>\n\t\t\t\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # todays date
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class='err'>Error : Customer not Found.</li>";
    }
    $cus = pg_fetch_array($custRslt);
    $na = $cus['surname'];
    # 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) {
        return "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $wtot = array_sum($totstkamt) + $va;
    $lwtot = sprint($wtot * $inv['xrate']);
    $lva = sprint($va * $inv["xrate"]);
    $tpp = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        writetrans($stkacc, $dept['debtacc'], $sndate, $refnum, $lwtot, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
    }
    if ($lva != 0) {
        writetrans($vatacc, $dept['debtacc'], $sndate, $refnum, $lva, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Vat. Customer {$inv['cusname']}.");
    }
    db_connect();
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$wtot}','{$sndate}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$sndate}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusid'], $dept['incacc'], $sndate, $real_noteid, "Non Stock Credit note {$real_noteid}", $lwtot, "c");
    frecordCT($wtot, $inv['cusid'], $inv['xrate'], $inv['fcid'], $sndate);
    // custCT($TOTAL, $inv['cusid']);
    db_connect();
    $sql = "UPDATE nons_invoices \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, location, currency, date, subtot, vat, total, username, prd, notenum, ctyp, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', 'int', '{$inv['currency']}', '{$sndate}', '" . sprint($wtot - $va) . "', {$va}, {$wtot}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    $noteid = pglib_lastid("nons_inv_notes", "noteid");
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
        $sql = "INSERT INTO nons_note_items(noteid, qty, description, amt, unitcost) \n\t\t\t\tVALUES('{$noteid}', '{$qtys[$key]}', '{$nstk['description']}', '{$amts[$key]}', \n\t\t\t\t\t'{$nstk['unitcost']}')";
        $stkdRslt = db_exec($sql);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$sndate}', '{$noteid}', '{$real_noteid}', '0', '{$lva}', '{$lwtot}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusid']}','{$na}','Credit note: {$real_noteid}, Non-stock International Invoice {$inv['invnum']} ','{$sndate}','" . -sprint($lwtot - $lva) . "','-{$lva}','" . -sprint($lwtot) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$sndate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\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<td>{$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>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</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>(Vat No. {$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' width='30%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\t\tVat No. " . COMP_VATNO . "\n\t\t\t\t\t\t\t</td>\n\t\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\t<td valign='bottom' align='right' width='20%'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$real_noteid}</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><b>Invoice No.</b></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>\n\t\t\t\t\t\t\t\t\t\t<td><b>Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$sndate}</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='4'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\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\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\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>{$inv['remarks']}</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\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\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><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\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\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\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\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.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 bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 4, "Invalid Reference number.");
    # 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;
    }
    # Get cash book record
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li class='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    $rate = sprint($accnt['amount'] / $accnt['famount']);
    # Update xrate
    if ($accnt['fcid'] != 0) {
        cus_xrate_update($accnt['fcid'], $rate);
        xrate_update($accnt['fcid'], $rate, "invoices", "invid");
        xrate_update($accnt['fcid'], $rate, "custran", "id");
        bank_xrate_update($accnt['fcid'], $rate);
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['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.";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    $date = $accnt["date"];
    # If tis customer payment
    if ($accnt['cusnum'] > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $famounts = explode("|", $accnt['famounts']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            db_connect();
            # Skip all nulls and check existance
            if ($invids[$key] > 0 && ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "UPDATE invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)), fbalance = (fbalance + '{$famounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
            } elseif ($invids[$key] > 0 && ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                db_connect();
                $sql = "UPDATE nons_invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)), fbalance = (fbalance + '{$famounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                frecordDTA($famounts[$key], $accnt['cusnum'], $rate, $rages[$key], $accnt['fcid']);
                // custDTA($amounts[$key], $accnt['cusnum'], $rages[$key]);
            } elseif ($invids[$key] > 0) {
                db_conn($invprds[$key]);
                # check if invoice exitsts on prd
                if (ext_ex("invoices", "invid", $invids[$key])) {
                    # if found, Move the invoice back
                    if (moveback($invids[$key], $invprds[$key], $famounts[$key], $amounts[$key])) {
                    }
                }
            }
        }
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        db_connect();
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the transaction on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$accnt['cusnum']}', '0', '{$accnt['famount']}','{$sdate}', 'Cheque/Payment for Invoices Cancelled.', '" . USER_DIV . "', '{$accnt['date']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            // Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        # Make ledge record
        custledger($accnt['cusnum'], $bank['accnum'], $sdate, "cancel", "Payment for Invoices Cancelled.", $accnt['amount'], "d");
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit customer account, credit bank account (customer takes money back)
        writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['supid'] > 0) {
        db_connect();
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $ids = explode("|", $accnt['ids']);
        $purids = explode("|", $accnt['purids']);
        $fpamounts = explode("|", $accnt['fpamounts']);
        $pamounts = explode("|", $accnt['pamounts']);
        $pdates = explode("|", $accnt['pdates']);
        if (count($ids) > 0) {
            foreach ($ids as $key => $vale) {
                if ($ids[$key] > 0) {
                    rerecord($ids[$key], $accnt['supid'], $purids[$key], $fpamounts[$key], $pamounts[$key], $pdates[$key]);
                }
            }
        }
        # if the amount was overpaid
        if (array_sum($fpamounts) < $accnt['famount']) {
            # get and record amount that was overpaid to balance the equation
            $rem = $accnt['famount'] - array_sum($fpamounts);
            rerecord('0', $accnt['supid'], '0', $rem, 0, $accnt['date']);
        }
        # Update the supplier (make balance more)
        $sql = "UPDATE suppliers SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$sdate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Cancelled.', '{$accnt['famount']}', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            // Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        suppledger($accnt['supid'], $bank['accnum'], $sdate, $accnt['cheqnum'], "Payment to Supplier Cancelled", $accnt['amount'], "c");
        db_connect();
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['suprec'] > 0) {
        db_connect();
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Cancelled','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        suppDT($accnt['amount'], $accnt['suprec']);
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if ($accnt['lcashid'] > 0) {
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif (strlen($accnt['accids']) > 0) {
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        multican($accnt, $bank, $vatacc);
    } else {
        $amount = $accnt['amount'];
        $vat = $accnt['vat'];
        $chrgvat = $accnt['chrgvat'];
        $amount -= $vat;
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['trantype'] == "deposit") {
            $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        } else {
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        }
        /* ---- the Others ---- */
        if ($accnt['lcashid'] > 0) {
            //Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            if ($laccnt['trantype'] == "deposit") {
                $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            } else {
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            }
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        /* ---- End the Others ---- */
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        if ($accnt['trantype'] == "deposit") {
            # DT(account involved), CT(bank)
            writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
        } else {
            # DT(bank), CT(account invoilved)
            writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($bank['accnum'], $vatacc, $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Cancelled Bank Transaction', '{$date}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    # Status report
    $bank = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Cash Book</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t</tr>\n\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width='90%'>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Navigation</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add bank Payment</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</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</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $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) {
            $v->isOk($qty, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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 error($_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 "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    $notenum = divlastid('note', USER_DIV);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $taxex = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE stkid = '{$stkids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Calculate the Discount discount
        if ($disc[$keys] < 1) {
            if ($discp[$keys] > 0) {
                $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
            }
        } else {
            $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
        }
        # Calculate amount
        $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $amt[$keys];
        }
        # put in product
        $products .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\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<td>{$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$keys]}'>{$inv['currency']} {$amt[$keys]}</td>\n\t\t\t\t\t\t</tr>";
    }
    # 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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($inv['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 ($inv['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);
    }
    $SUBTOTAL = sprint($SUBTOT);
    $traddiscm = $traddiscmt;
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = sprint(array_sum($amt));
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = sprint($SUBTOT);
    
    		$VATP = TAX_VAT;
    		if($inv['chrgvat'] == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($inv['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);
    
    		$traddiscm = $traddiscmt;
    
    		if($inv['chrgvat'] != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $FSUBTOT = sprint($SUBTOT * $inv['xrate']);
    $FSUBTOTAL = sprint($SUBTOTAL * $inv['xrate']);
    $FVAT = sprint($VAT * $inv['xrate']);
    $FTOTAL = sprint($TOTAL * $inv['xrate']);
    $fdelchrg = sprint($delchrg * $inv['xrate']);
    $ftraddiscm = sprint($traddiscm * $inv['xrate']);
    /* --- ----------- Clac --------------------- */
    # 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 class=err>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    /* A quick fix by jupiter
    	$allnoted = true;
    	foreach($qtys as $keys => $value){
    		# get selected stock in this invoice
    		$sql = "SELECT * FROM inv_items  WHERE id = '$ids[$keys]' AND invid ='$invid' AND div = '".USER_DIV."'";
    		$stkdRslt = db_exec($sql);
    		$stkd = pg_fetch_array($stkdRslt);
    		if($stkd['qty'] != $qtys[$keys]){
    			$allnoted = false;
    		}
    	}
    
    	if($allnoted){
    		$SUBTOT = sprint($inv['subtot']);
    		$VAT = sprint($inv['vat']);
    		$TOTAL = sprint($inv['total']);
    		$delchrg = sprint($inv['delivery']);
    		$traddiscm = sprint($inv['discount']);
    		$SUBTOTAL = sprint($TOTAL - $VAT);
    
    		$FSUBTOT = sprint($SUBTOT * $inv['xrate']);
    		$FSUBTOTAL = sprint($SUBTOTAL * $inv['xrate']);
    		$FVAT = sprint($VAT * $inv['xrate']);
    		$FTOTAL = sprint($TOTAL * $inv['xrate']);
    		$fdelchrg = sprint($delchrg * $inv['xrate']);
    		$ftraddiscm = sprint($traddiscm * $inv['xrate']);
    	}
    /*End A quick fix by jupiter */
    $invpay = $TOTAL;
    /*if($inv['fbalance'] >= $TOTAL) {
    		$invpay = $TOTAL;
    		$examt = 0;
    	} else {
    		$invpay = $inv['fbalance'];
    		$examt = ($TOTAL-$invpay);
    	}
    
    	# Make it local
    	 $examt = ($examt * $inv['xrate']);*/
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    # Insert invoice to period DB
    db_conn($inv['prd']);
    # Format date
    $odate = explode("-", $odate);
    $rodate = $odate[2] . "-" . $odate[1] . "-" . $odate[0];
    $td = $rodate;
    # Insert invoice credit note to DB
    $sql = "INSERT INTO inv_notes(deptid, notenum, invnum, invid, cusnum, cordno, ordno, chrgvat, fcid, currency, xrate, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, comm, username, div, surname, cusaddr, cusvatno, deptname, location, prd)";
    $sql .= " VALUES('{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}', '{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', '{$inv['chrgvat']}', '{$inv['fcid']}', '{$inv['currency']}', '{$inv['xrate']}', '{$terms}', '{$traddiscm}', '{$inv['salespn']}', '{$rodate}', '{$delexvat}', '{$SUBTOT}', '{$VAT}' , '{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "', '{$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['deptname']}', '{$inv['location']}', {$inv['prd']})";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $nbal = $inv['nbal'] + $TOTAL;
    # Update the invoice (make balance less)
    $sql = "UPDATE invoices SET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), fbalance = fbalance - '{$invpay}', balance = balance - '{$FTOTAL}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers SET balance = (balance - '{$FTOTAL}'), fbalance = (fbalance - '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update invoice's discounts
    # $sql = "UPDATE inv_discs SET traddisc = (traddisc - '$traddiscm'), itemdisc = (itemdisc - '$discs') WHERE cusnum = '$inv[cusnum]' AND invid = '$invid'";
    # $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$inv['cusnum']}','{$inv['invnum']}','" . ($TOTAL - $TOTAL * 2) . "', '{$rodate}', 'Credit Note for invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$rodate}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $disc = 0;
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $notenum, "Credit Note No. {$notenum} for invoice No. {$inv['invnum']}", $FTOTAL, "c");
    /*
    if($examt > 0) {
    	# Make record for age analisys
    	custCTP($examt, $inv['cusnum']);
    }
    */
    foreach ($qtys as $keys => $value) {
        $famt[$keys] = sprint($amt[$keys] * $inv['xrate']);
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'] * $inv['xrate'];
        # cost amount
        $cosamt = round($qtys[$keys] * $stk['csprice'], 2);
        # Update stock(onhand + qty)
        $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if ($stk['serd'] == 'yes') {
            ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $td);
        }
        # negetive values to minus profit
        $nqty = $qtys[$keys] * 1;
        $namt = $amt[$keys] * -1;
        $ncsprice = $cosamt * -1;
        $noted = $stkd['noted'] + $qtys[$keys];
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = $famt[$keys];
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes' && $vd['zero'] != "Yes") {
            $amtexvat = sprint($famt[$keys] * 100 / (100 + $VATP));
        }
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
        ####################################################
        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', '{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # Get selected stock in this invoice
        $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdsRslt = db_exec($sql);
        $stkds = pg_fetch_array($stkdsRslt);
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # sales rep commission
        # coms($inv['salespn'], $amt[$keys], $stk['com'], 'anything');
        # dt(stock) ct(cos)
        writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
        db_conn($inv['prd']);
        # insert invoice items
        $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div,vatcode) VALUES('{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "','{$stkd['vatcode']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    db_connect();
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div) VALUES('{$inv['cusnum']}', '{$invid}', '0', '-{$disc}', '{$inv['odate']}', '0', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    /* - Start Transactoins - */
    # dt(income) ct(debtors)
    writetrans($dept['incacc'], $dept['debtacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $FVAT, "Vat Return for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $date = date("Y-m-d");
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'nstk', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['surname']}','Credit Note: {$notenum}, International Invoice {$inv['invnum']}','{$rodate}','" . -sprint($FTOTAL - $FVAT) . "','-{$FVAT}','" . -sprint($FTOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width=750>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\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<td>{$inv['surname']}</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>" . nl2br($inv['cusaddr']) . "</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>(Vat No. {$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' width='25%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t</td>\n\t\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\t<td valign='bottom' align='right' width='25%'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$notenum}</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><b>Invoice No.</b></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>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</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><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$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>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit note Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$rodate}</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='4'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY RETURNED</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\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>\n\t\t\t\t\t\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr><td>" . nl2br($comm) . "</td></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 align='right' colspan='3'>\n\t\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\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\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\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><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$traddiscmt}</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><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$delexvat}</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><b>VAT @ {$VATP}%</b></td>\n\t\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\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\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\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></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 . " border=1>\n\t\t\t\t\t\t        \t<tr>\n\t\t\t\t\t\t        \t\t<th>VAT No.</th>\n\t\t\t\t\t\t        \t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t        \t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = "<script>printer('intinvoice-note-reprint.php?noteid={$noteid}&prd={$inv['prd']}&cccc=yes');move('main.php');</script>";
    require "template.php";
}