function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitamts[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    $prd += 0;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier");
    if (pg_numrows($supRslt) < 1) {
        $error = "<li class='err'> Supplier not Found.</li>";
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    } else {
        $sup = pg_fetch_array($supRslt);
        $pur['supplier'] = $sup['supname'];
        $pur['supaddr'] = $sup['supaddr'];
        # Get department info
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$sup['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);
        }
        $supacc = $dept['credacc'];
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    $retax = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            db_conn($prd);
            $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # the unitcost + delivery charges * qty
            $famt[$keys] = sprint($unitamts[$keys] * $qtys[$keys]);
            # calculate tax
            $ftaxes[$keys] = svat($famt[$keys], $pur['subtot'], $pur['tax']);
            $amt[$keys] = sprint($unitamts[$keys] * $pur['xrate'] * $qtys[$keys]);
            # calculate tax
            $retax += sprint($ftaxes[$keys] * $pur['xrate']);
            # Update Order items
            $sql = "UPDATE nons_purint_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
        }
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $refnum = getrefnum();
    $sdate = $pur["pdate"];
    //$ddate;
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($supacc, $stkacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Returned to Supplier {$sup['supname']}.");
    }
    db_connect();
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['cusid']}'";
    $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 ($retax > 0) {
        writetrans($supacc, $vatacc, date("d-m-Y"), $refnum, $retax, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.");
    }
    $retot = sprint(array_sum($amt) + $retax);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.", $retot, $retax);
    $fretot = sprint(array_sum($famt) + array_sum($ftaxes));
    suppledger($sup['supid'], $stkacc, $sdate, $pur['purid'], "Returned, Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'd');
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}'), fbalance = (fbalance - '{$fretot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$sdate}', '{$dept['credacc']}', '-{$fretot}','Returned, Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    # make transaction record for age analysis
    $sql = "INSERT INTO suppurch(supid, purid, pdate, fcid, balance, fbalance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$sdate}', '{$pur['fcid']}', '-{$retot}', '-{$fretot}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # if none the set to received
    if (pg_numrows($stkdRslt) < 1) {
        # update surch_int(received = 'y')
        $sql = "UPDATE nons_purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        //$rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.",SELF);
    }
    # Update Order on the DB
    $sql = "UPDATE nons_purch_int SET refno = '{$refno}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.",SELF);
    /* End Transactions */
    /* Start moving if Order received */
    db_conn($prd);
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $rdate = date("Y-m-d");
    # copy Order
    db_conn($prd);
    $sql = "INSERT INTO rnons_purch_int(purid, deptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, curr, currency, shipping, subtot, total, balance, tax, remarks, refno, received, done, div, purnum, rdate)";
    $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['currency']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['tax']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$rdate}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    db_connect();
    db_conn($prd);
    # get selected stock
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        # Insert Order items
        db_conn($prd);
        $sql = "INSERT INTO rnons_purint_items(purid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, accid, div) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['accid']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
    }
    db_connect();
    # Remove the Order from running DB
    $sql = "DELETE FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Remove those Order items from running DB
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving Order received */
    $cc = "<script> CostCenter('dt', 'Returned, International Non-Stock Purchase', '{$pur['pdate']}', 'Returned, Non Stock Purchase No.{$pur['purnum']}', '" . sprint($retot - $retax) . "', ''); </script>";
    // Final Layout
    $write = "{$cc}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>International Non-Stock Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Non-Stock Order receipt has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purch-int-view.php'>View International Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class=err>" . $e["msg"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $td = $date;
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($suppRslt) < 1) {
        return "<li> Invalid Supplier ID.";
    } else {
        $supp = pg_fetch_array($suppRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class=err>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    # update all supplies xchange rate first
    xrate_update($supp['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($supp['fcid'], $rate);
    $supp['supname'] = remval($supp['supname']);
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['credacc'], $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td><td>{$supp['supno']} - {$supp['supname']}</td></tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordCT(-$amount, $supp['supid']);
        frecordCT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$supp['supno']} - {$supp['supname']}</td><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td></tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordDT($amount, $supp['supid']);
        frecordDT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $edate = date("Y-m-d");
    # record the payment on the statement
    $sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$supp['supid']}', '{$td}', '0', '{$accid}', '{$details}', '{$sfamt}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$samount}'),fbalance = (fbalance + '{$sfamt}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Ledger Records
    suppledger($supp['supid'], $accid, $td, $refnum, $details, $amount, $type);
    db_connect();
    // Start layout
    $write = "<h3>Journal transaction has been recorded</h3>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n\t\t{$tran}\n\t\t<tr><td><br></td></tr>\n\t\t<tr colspan=2><td><h4>Amount</h4></td></tr>\n\t\t<tr class='bg-even'><td colspan=2><b>" . CUR . " {$famt}</b></td></tr>\n\t</table>\n\t<P>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../supp-view.php'>View Suppliers</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_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 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($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $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"] . "</li>";
        }
        $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) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    db_connect();
    # Supplier name
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    xrate_update($sup['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($sup['fcid'], $rate);
    bank_xrate_update($sup['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_connect();
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $lamt, "d");
        db_connect();
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $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, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid']);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid']);
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid']);
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid']);
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' 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, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $lamt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        #pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $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.";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc,div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment - Purchase: {$invids[$key]}','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' 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, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['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.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        #pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE fbalance = 0::numeric(13,2) AND balance = 0::numeric(13,2)";
    $Rx = db_exec($Sl);
    # status report
    $write = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t<tr>\n\t\t\t<th>International Bank Payment</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Bank Payment added to cash book.</td>\n\t\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n\t<table width='90%'>\n\t\t<tr valign='top'>\n\t\t\t<td width='50%'>{$write}</td>\n\t\t\t<td align='center'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-supp.php'>Add supplier payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    # check if Order has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Transactions --- */
    db_conn(PRD_DB);
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $taxamt = $pur['tax'] * -1;
    $ltotal = sprint($pur['total'] * $pur['xrate']);
    $ltax = sprint($pur['tax'] * $pur['xrate']);
    db_connect();
    # update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    # Update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$ltotal}'), fbalance = (fbalance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $DAte = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}','{$pur['total']}','International - Stock Received', '{$refnum}','{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['jobnum']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -($ltotal + $ltax), -$ltax);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $pur['pdate'], $refnum, $ltotal - $ltax, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    # Debit bank and credit the account involved
    writetrans($vatacc, $dept['credacc'], $pur['pdate'], $refnum, $ltax, "Tax Paid on International Orders No. {$pur['purnum']} from Supplier {$sup['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $pur['pdate'], $pur['purid'], "International Order No. {$pur['purnum']} received.", $ltotal, 'c');
    db_connect();
    /* --- End Transactions --- */
    /* Make transaction record  for age analysis */
    $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, fcid, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$ltotal}', '{$pur['fcid']}', '{$pur['total']}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    /* Make transaction record  for age analysis */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if Order received and invoiced */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # Copy Order
        db_conn($pur['prd']);
        $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['tax']);
        $nsubtot = sprint($nsubtot * $pur['xrate']);
        if ($pur['rlsubtot'] > $nsubtot) {
            $diff = sprint($pur['rlsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rlsubtot']) {
            $diff = sprint($nsubtot - $pur['rlsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where Order is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    } else {
        # Insert Order to DB
        $sql = "UPDATE purch_int SET invcd = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>International Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}