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.");
    $ddate = $d_year . "-" . $d_month . "-" . $d_day;
    if (!checkdate($d_month, $d_day, $d_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] < 1) {
                $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    //print $td; exit;
    # 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);
    $TD = $pur["pdate"];
    # 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>";
    }
    # check if Order has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected 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");
    $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);
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn(PRD_DB);
    # get last ref number
    $refnum = getrefnum();
    db_connect();
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    foreach ($recvd as $sk => $keys) {
        if ($qtys[$keys] < 1) {
            continue;
        }
        /* -- Calculations -- */
        # Calculate cost amount bought
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        $amt[$keys] += $duty[$keys] * $pur['xrate'];
        # Calculate percentage from subtotal
        $perc[$keys] = $amt[$keys] / ($pur['subtot'] * $pur['xrate']) * 100;
        # Get percentage from shipping charges
        $shipchrg[$keys] = $perc[$keys] / 100 * ($pur['shipchrg'] * $pur['xrate']);
        # add shipping charges to amt
        $amt[$keys] = round($amt[$keys] + $shipchrg[$keys], 2);
        $resub += $amt[$keys];
        /* -- End Calculations --*/
        # 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);
        if ($stk['units'] < 0) {
            $min_stock = abs($stk['units']);
            if ($qtys[$keys] < $min_stock) {
                $min_stock = $qtys[$keys];
            }
        } else {
            $min_stock = 0;
        }
        # Update Order items
        $sql = "UPDATE purint_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        # update stock(ordered + qty, units + qty, csamt + (csamt + amt))
        $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (isset($sers[$stkids[$keys]][$keys])) {
            ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $sup['supname'], $pur['purnum'], "pur", $TD);
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
        }
        # get selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $TD, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}");
        db_connect();
        $cspric = sprint($amt[$keys] / $qtys[$keys]);
        $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']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # Just wanted to fix the xxx.xxxxxxe-x value
        # $csprice = round(($stk['csamt']/$stk['units']), 2);
        if ($stk['units'] > 0) {
            $csprice = round($stk['csamt'] / $stk['units'], 2);
        } else {
            $csprice = round($stk['csprice'], 2);
        }
        # update stock(csprice = (csamt/units))
        $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # check if there are any outstanding items
        $sql = "SELECT * FROM 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 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);
        }
    }
    if ($min_stock > 0) {
        $cost = sprint($unitcost[$keys] * $min_stock);
        $td = "{$d_year}-{$d_month}-{$d_day}";
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        db_connect();
        $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'";
        $Ri = db_exec($Sl);
        writetrans($cosacc, $stockacc, $TD, $refnum, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}");
        db_connect();
        $Sl = "INSERT INTO pcost(purnum,cost,qty,rqty,stkid) VALUES ('{$pur['purnum']}','{$unitcost[$keys]}','{$min_stock}','0','{$stk['stkid']}')";
        $Ri = db_exec($Sl);
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    # Update Order on the DB
    $fresub = sprint($resub / $pur['xrate']);
    $sql = "UPDATE purch_int SET rsubtot = (rsubtot + '{$fresub}'), rlsubtot = (rlsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', ddate = '{$ddate}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", 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 transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # Get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Debit Stock and Credit Suppliers control
        writetrans($wh['stkacc'], $wh['conacc'], $TD, $refnum, $wamt, "International Stock Order No. {$pur['purnum']} Received from Supplier {$sup['supname']}.");
    }
    # 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" && $pur['invcd'] == '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, $TD, $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'], $TD, $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);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>International Order received</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $write;
}
function printSerial($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($serno, "string", 1, 10, "Invalid Serial number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($serno, $confirm);
    }
    $serlist = "";
    $details = "no details";
    db_connect();
    $sql = "SELECT * FROM serialrec WHERE serno LIKE '%{$serno}%' AND div = '" . USER_DIV . "' ORDER BY recid ASC";
    $serRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
    if (pg_numrows($serRslt) > 0) {
        while ($ser = pg_fetch_array($serRslt)) {
            $stk = qryStock($ser["stkid"]);
            switch ($ser['typ']) {
                case "inv":
                    $details = "Invoiced to {$ser['cusname']} Invoice No. {$ser['invnum']}";
                    break;
                case "note":
                    $details = "Received from {$ser['cusname']} Credit Note No. {$ser['invnum']}";
                    break;
                case "pur":
                    $details = "Purchased from Supplier {$ser['cusname']} Purchase No. {$ser['invnum']}";
                    break;
                case "ret":
                    $details = "Returned to Supplier {$ser['cusname']} Purchase No. {$ser['invnum']}";
                    break;
                case "tran":
                    $details = "Stock Decrease Transaction : {$ser['cusname']}";
                    break;
            }
            $ser['edate'] = ext_rdate($ser['edate']);
            $serlist .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$ser['serno']}</td>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td>{$details}</td>\n\t\t\t\t\t<td align='center'>&nbsp;&nbsp;&nbsp;{$ser['tdate']}&nbsp;&nbsp;&nbsp;</td>\n\t\t\t\t\t<td>{$stk['warranty']}</td>\n\t\t\t\t</tr>";
        }
    } elseif (ext_findSer($serno)) {
        $sers = ext_findSer($serno);
        foreach ($sers as $key => $ser) {
            # Get selected stock
            db_connect();
            $sql = "SELECT stkdes,stkcod FROM stock WHERE stkid = '{$ser['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $serlist .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$ser['serno']}</td>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td align='center'>Available</td>\n\t\t\t\t\t<td align='center'>---</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
        }
    } else {
        $err = "<li class='err'>Serial Number <b>{$serno}</b> not found.</li>";
        return slct($serno, $err);
    }
    $serials = "\n\t\t<center>\n\t\t<h3>Stock Serial Numbers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Serial No.</th>\n\t\t\t\t<th>Stock Code</th>\n\t\t\t\t<th>Stock Description</th>\n\t\t\t\t<th>Details</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Warranty</th>\n\t\t\t</tr>\n\t\t\t{$serlist}\n\t\t\t<tr><td><br></td></tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='" . SELF . "'>Find Another</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $serials;
}
function 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($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] < 1) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Validate ddate[]
            $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day.");
            $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month.");
            $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year.");
            $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys];
            if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) {
                $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date.");
            }
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    /* check quantities
    	if(isset($qtys)){
    		foreach($qtys as $keys => $qty){
    			$v->isOk ($qty, "num", 1, 10, "Invalid Quantity for product number : <b>".($keys+1)."</b>");
    			$v->isOk ($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>.");
    			if($qty > $qts[$keys]){
    				$v->isOk ($qty, "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>".($keys+1)."</b>");
    			}
    		}
    	}
    
    	# check stkids
    	if(isset($stkids)){
    		foreach($stkids as $keys => $stkid){
    			$v->isOk ($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
    		}
    	}*/
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT deptname 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);
    }
    core_connect();
    # Get Petty cash account
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    # Insert purchase to DB
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    $taxex = 0;
    $revat = 0;
    # Get subtotal
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
    }
    $SUBTOTAL = array_sum($amt);
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        # 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 line
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # Calculate cost amount bought
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        /* delivery charge */
        # Calculate percentage from subtotal
        $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
        # Get percentage from shipping charges
        $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
        # Add delivery charges
        $amt[$keys] += $shipc[$keys];
        /* end delivery charge */
        # the subtotal + delivery charges
        $resub += $amt[$keys];
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes') {
            # how much is not vatable?
            $taxex += $amt[$keys];
        } else {
            # Line vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
        }
        # Update purchase items
        $sql = "UPDATE pur_items SET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$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);
        # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
        $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}'), csamt = (csamt + '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (isset($sers[$stkids[$keys]][$keys])) {
            ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $pur['pdate']);
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # Get selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}");
        db_connect();
        $cspric = sprint($amt[$keys] / $qtys[$keys]);
        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # Just wanted to fix the xxx.xxxxxxe-x value
        if ($stk['units'] > 0) {
            $csprice = round($stk['csamt'] / $stk['units'], 2);
        } else {
            $csprice = round($stk['csprice'], 2);
        }
        # update stock(csprice = (csamt/units))
        $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # check if there are any outstanding items
        $sql = "SELECT * FROM pur_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 purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
        }
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "UPDATE purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'";
    } else {
        $sql = "UPDATE purchases SET shipchrg = '{$shipchrg}', part = 'y', refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $tpp = 0;
    # Record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # Get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Debit Stock and Petty Cash acc
        writetrans($wh['stkacc'], $cashacc, date("d-m-Y"), $refnum, $wamt, "Stock Received for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.");
    }
    # Calc Vat amount on (subtot + delchrg)
    # $vatamt = vat(($resub - $taxex), $pur['vatinc']);
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } else {
        $retot = $resub;
    }
    # Transfer vat
    writetrans($vatacc, $cashacc, date("d-m-Y"), $refnum, $vatamt, "Vat Paid for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.");
    db_connect();
    # Record tranfer for patty cash report
    $sdate = date("Y-m-d");
    $sql = "INSERT INTO pettyrec(date, type, det, amount, name, div) VALUES ('{$sdate}', 'Req', 'Cash Payment for Stock Received on Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.', '-{$retot}', 'Petty Cash Purchase', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # copy purchase
        db_conn($pur['prd']);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Order information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Order information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    // Final Layout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Order receipt from Supplier <b>{$pur['supname']}</b> 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='purchase-view.php'>View Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    // 	print "<pre>";
    // 	print_r ($_POST);
    // 	print "</pre>";
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # Used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qtys[$keys] < 1) {
                $v->isOk("#", "float", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                foreach ($recvd as $sk => $keys) {
                    if (isset($sernos[$keys]) && strlen($sernos[$keys]) < 1) {
                        $v->isOk("#", "string", 1, 20, "Error : Invalid Serial number.");
                    }
                    if (isset($sernos[$keys]) && strlen($sernos[$keys]) > 0 && ext_findSer($sernos[$keys]) == false) {
                        $v->isOk("#", "string", 1, 20, "Error : Serial <b>{$sernos[$keys]}</b> does not exists.");
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # 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 purchase info
    db_conn($prd);
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase 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 customer information");
    $sup = pg_fetch_array($supRslt);
    # Get department info
    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);
    }
    # Insert purchase to DB
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    $taxex = 0;
    # amount of stock in
    $totstkamt = array();
    foreach ($recvd as $sk => $keys) {
        if ($qtys[$keys] < 1) {
            continue;
        }
        # Get csprice from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        db_conn($prd);
        # Get selected stock
        $sql = "SELECT * FROM purint_items WHERE stkid = '{$stkids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # Calculate the unitcost
        $unitcost[$keys] = $stk['csprice'];
        $cunitcost[$keys] = $stk['csprice'] / $pur['xrate'];
        $cunitcost[$keys] = $stkd['cunitcost'];
        $unitcost[$keys] = $stkd['unitcost'];
        # Calculate amount
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        $famt[$keys] = $qtys[$keys] * $cunitcost[$keys];
        // 			db_conn($prd);
        // 			# Get selected stock
        // 			$sql = "SELECT * FROM purint_items WHERE stkid = '$stkids[$keys]' AND purid = '$purid' AND div = '".USER_DIV."'";
        // 			$stkdRslt = db_exec($sql);
        // 			$stkd = pg_fetch_array($stkdRslt);
        db_conn($prd);
        # Update order items
        $sql = "UPDATE purint_items SET tqty = (tqty + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$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[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # Update stock(units - qty), csamt = (csamt - amt)
        db_connect();
        $sql = "UPDATE stock SET units = (units - '{$qtys[$keys]}'), csamt = (csamt - '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (isset($sers[$stkids[$keys]][$keys])) {
            ext_OutSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $sup['supname'], $pur['purnum'], "ret");
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "DELETE FROM pserec WHERE purid = '{$purid}' AND  stkid = '{$stkids[$keys]}' AND serno = '{$serial}'";
            $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
        }
        # Get selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # Just wanted to fix the xxx.xxxxxxe-x value
        if ($stk['units'] > 0) {
            $csprice = round($stk['csamt'] / $stk['units'], 2);
        } else {
            $csprice = 0;
        }
        # Update stock(csprice = (csamt/units))
        $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $pdate, $qtys[$keys], $amt[$keys], "Stock returned to Supplier : {$sup['supname']} - Purchase No. {$pur['purnum']}.");
        db_connect();
    }
    /* --- Clac --- */
    $xrate = $pur['xrate'];
    # Calculate subtot
    if (isset($famt)) {
        $SUBTOT = array_sum($famt);
    } else {
        $SUBTOT = 0.0;
    }
    $tax = 0;
    /* --- End Clac --- */
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purch_int SET rsubtot = (rsubtot + '{$SUBTOT}'), rtax = (rtax + '{$tax}'), remarks = '{$remarks}' WHERE purid = '{$pur['purid']}'";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    # Insert returned purchase
    $sql = "INSERT INTO purchint_ret(purid, purnum, supname, rdate, subtot, remarks, div)\n\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$sup['supname']}', '{$pdate}', '{$SUBTOT}', '{$remarks}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    $rpurid = pglib_lastid("purchint_ret", "rpurid");
    # Insert returned items
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        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);
        db_conn($prd);
        $sql = "INSERT INTO retpurint_items(rpurid, whid, stkid, qty, unitcost)\n\t\t\tVALUES('{$rpurid}', '{$stk['whid']}', '{$stk['stkid']}', '{$qtys[$keys]}', '{$unitcost[$keys]}')";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    $refnum = getrefnum();
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # Record transaction from data
    foreach ($totstkamt as $whid => $wamt) {
        # get whouse info
        db_conn("exten");
        $sql = "SELECT conacc,stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Debit Suppliers control and Credit Stock
        writetrans($wh['conacc'], $wh['stkacc'], $pdate, $refnum, $wamt, "Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}");
    }
    /* End Transactions */
    /* End Transactions */
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND (qty - tqty) > 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 purch_int SET returned = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Stock Return</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock Return to 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='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    $TOTALs += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # Used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qtys[$keys] <= 0) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                foreach ($recvd as $sk => $keys) {
                    if (isset($sernos[$keys]) && strlen($sernos[$keys]) < 1) {
                        $v->isOk("#", "string", 1, 20, "Error : Invalid Serial number.");
                    }
                    if (isset($sernos[$keys]) && strlen($sernos[$keys]) > 0 && ext_findSer($sernos[$keys]) == false) {
                        $v->isOk("#", "string", 1, 20, "Error : Serial <b>{$sernos[$keys]}</b> does not exists.");
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # 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);
    }
    if (!isset($del)) {
        $del = "";
    }
    $del += 0;
    # Get purchase info
    db_conn($prd);
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Purchase 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 purchase has been received
    if ($pur['received'] == "n") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has not been received.";
        $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 info
    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);
    }
    $pur['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $VATP = $vd['vat_amount'];
    if ($vd['zero'] != "Yes") {
        //	$VATP = TAX_VAT;
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $del);
            $delexvat = $del;
            $scvat = sprint($VATP / 100 * $cost);
            $costexvat = $cost;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($del / ($VATP + 100) * $VATP);
            $delexvat = $del - $scvat;
            $scvat = sprint($cost / ($VATP + 100) * $VATP);
            $costexvat = $cost - $scvat;
        } else {
            $scvat = 0;
            $costexvat = $cost;
        }
    } else {
        //$VATP = TAX_VAT;
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $del);
            $delexvat = $del;
            $scvat = sprint($VATP / 100 * $cost);
            $costexvat = $cost;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($del / ($VATP + 100) * $VATP);
            $delexvat = $del;
            $scvat = sprint($cost / ($VATP + 100) * $VATP);
            $costexvat = $cost - $scvat;
        } else {
            $scvat = 0;
            $costexvat = $cost;
        }
    }
    //$cost=$cost+$delexvat;
    //2631.58
    # Insert purchase to DB
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    db_connect();
    $taxex = 0;
    # amount of stock in
    $totstkamt = array();
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] <= 0) {
            continue;
        }
        db_conn($prd);
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        $stkd = pg_fetch_array($rslt);
        if ($stkd['stkid'] < 1) {
            $stk['whid'] = $stkd['account'];
            $unitcost[$keys] = $stkd['unitcost'];
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                $Sl = "SELECT * FROM vatcodes";
                $Ri = db_exec($Sl);
            }
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            //	$VATP = TAX_VAT;
            if ($pur['vatinc'] == "yes") {
                $uc = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
            } else {
                $uc = sprint($stkd['amt'] / $stkd['qty']);
            }
            $perc[$keys] = sprint($uc / $cost * 100);
            $shipc[$keys] = sprint($perc[$keys] / 100 * $delexvat);
            $unitcost[$keys] += $shipc[$keys];
            # including shipchrg, exluding vat
            $amts[$keys] = sprint($qtys[$keys] * $uc);
            //$amts[$keys] -= $vat[$keys];
            if (isset($totstkamt[$stk['whid']])) {
                $totstkamt[$stk['whid']] += $amts[$keys];
            } else {
                $totstkamt[$stk['whid']] = $amts[$keys];
                // + $vat[$keys];
            }
            $totstkamt[$stk['whid']] = sprint($totstkamt[$stk['whid']]);
            db_conn($prd);
            $sql = "\n\t\t\t\t\tUPDATE pur_items \n\t\t\t\t\tSET tqty = (tqty + '{$qtys[$keys]}'), ctqty = (ctqty + {$qtys[$keys]}) \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        } else {
            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);
            $unitcost[$keys] = $stkd['unitcost'];
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                $Sl = "SELECT * FROM vatcodes";
                $Ri = db_exec($Sl);
            }
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            //$VATP = TAX_VAT;
            if ($pur['vatinc'] == "yes") {
                $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
            } else {
                $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']);
            }
            $cost = $cost - $delexvat;
            //print "cost$cost/unicost $unitcost[$keys]";
            $perc[$keys] = sprint($unitcost[$keys] * $qtys[$keys] / $cost * 100);
            $shipc[$keys] = sprint($perc[$keys] / 100 * $delexvat);
            $cost = $cost + $delexvat;
            # including shipchrg, exluding vat
            $amts[$keys] = sprint($qtys[$keys] * $unitcost[$keys]);
            $amts[$keys] += $shipc[$keys];
            //$amts[$keys]-=$vat[$keys];
            //print "Per$perc[$keys]  Amount$amts[$keys]<br>";
            $Sl = "SELECT * FROM pcost WHERE purnum='{$pur['purnum']}' AND stkid='{$stk['stkid']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                db_conn("exten");
                $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                $stockacc = $wh['stkacc'];
                $cosacc = $wh['cosacc'];
                if ($pd['qty'] - $pd['rqty'] < $qtys[$keys] - $stk['units']) {
                    $qt = $pd['qty'] - $pd['rqty'];
                } else {
                    $qt = $qtys[$keys] - $stk['units'];
                }
                $cost = $pd['cost'] * $qt;
                writetrans($stockacc, $cosacc, date("d-m-Y"), $refnum, $cost, "Reverse Cost Of Sales for stock sold before purchase {$pur['purnum']}");
                db_conn('cubit');
                $Sl = "UPDATE pcost SET rqty=rqty+'{$qt}' WHERE purnum='{$pur['purnum']}'";
                $Ri = db_exec($Sl);
                $lc = $amts[$keys] - $cost;
            } else {
                $lc = $amts[$keys];
            }
            # Update purchase items
            db_conn($prd);
            $sql = "\n\t\t\t\t\tUPDATE pur_items \n\t\t\t\t\tSET tqty = (tqty + '{$qtys[$keys]}'), ctqty = (ctqty + {$qtys[$keys]}) \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
            # Update stock(units - qty), csamt = (csamt - amt)
            db_connect();
            $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET units = (units - '{$qtys[$keys]}'), csamt = (csamt - '{$lc}') \n\t\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if (isset($sers[$stkids[$keys]][$keys])) {
                ext_OutSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "ret");
                $serial = $sers[$stkids[$keys]][$keys];
                db_connect();
                $sql = "DELETE FROM pserec WHERE purid = '{$purid}' AND  stkid = '{$stkids[$keys]}' AND serno = '{$serial}'";
                $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            //	stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $qtys[$keys], $lc,"Stock returned to Supplier : $sup[supname] - Purchase No. $pur[purnum].");
            //$amts[$keys] = $lc
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $pur['pdate'], $qtys[$keys], $amts[$keys], "Stock returned to Supplier : {$sup['supname']} - Purchase No. {$pur['purnum']}.");
            db_connect();
            $cspric = sprint($amts[$keys] / $qtys[$keys]);
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '-{$qtys[$keys]}', '{$lc}', '{$cspric}', 'Stock Returned to Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Keep records for transactions
            if (isset($totstkamt[$stk['whid']])) {
                $totstkamt[$stk['whid']] += $amts[$keys];
            } else {
                $totstkamt[$stk['whid']] = $amts[$keys];
            }
            $totstkamt[$stk['whid']] = sprint($totstkamt[$stk['whid']]);
            # Get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # Just wanted to fix the xxx.xxxxxxe-x value
            if ($stk['units'] > 0) {
                $csprice = sprint($stk['csamt'] / $stk['units']);
            } else {
                $csprice = 0;
            }
            # Update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    /* --- Clac --- */
    # calculate subtot exluding vat
    $SUBTOT = sprint(array_sum($amts));
    // Excluding shipping charges
    /* --- End Clac --- */
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purchases SET rsubtot = (rsubtot + {$SUBTOT}) WHERE purid = '{$purid}'";
    # we dont want to change the old remark ???? just add the new 1 to the returned table data
    // , remarks = '$remarks'
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    # Insert returned purchase
    $sql = "\n\t\t\tINSERT INTO purch_ret (\n\t\t\t\tpurid, purnum, supname, rdate, subtot, remarks, div, supinv\n\t\t\t) VALUES (\n\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$sup['supname']}', '{$pdate}', '{$SUBTOT}', '{$remarks}', '" . USER_DIV . "', '{$pur['supinv']}'\n\t\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    $rpurid = pglib_lastid("purch_ret", "rpurid");
    # Insert returned items
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        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);
        if (!isset($stk['whid'])) {
            $stk['whid'] = 0;
            $stk['stkid'] = 0;
        }
        db_conn($prd);
        $sql = "\n\t\t\t\tINSERT INTO retpur_items (\n\t\t\t\t\trpurid, whid, stkid, qty, unitcost, itemid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$rpurid}', '{$stk['whid']}', '{$stk['stkid']}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$ids[$keys]}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # Record transaction from data
    foreach ($totstkamt as $whid => $wamt) {
        # get whouse info
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        if (pg_num_rows($whRslt) < 1) {
            $sql = "SELECT stkacc,conacc FROM warehouses";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $wh['stkacc'] = $whid;
        } else {
            $wh = pg_fetch_array($whRslt);
        }
        # Debit Suppliers control and Credit Stock
        //writetrans($wh['conacc'], $wh['stkacc'], date("d-m-Y"), $refnum, $wamt, "Stock Return on Purchase No. $pur[purnum] from Supplier : $sup[supname]");
        writetrans($wh['conacc'], $wh['stkacc'], $pdate, $refnum, $wamt, "Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}");
    }
    /* End Transactions */
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND (qty - tqty) > 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 purchases SET returned = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
    }
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t<script>\n\t\t\tprinter ('purch-return-print.php?purid={$purid}');\n\t\t</script>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Stock Return</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock Return to 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='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
Ejemplo n.º 6
0
function write()
{
    # Get vars
    extract($_REQUEST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] <= 0) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Validate ddate[]
            $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day.");
            $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month.");
            $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year.");
            $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys];
            if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) {
                $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date.");
            }
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # 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 purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected 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 info
    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);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $VATP = $vd['vat_amount'];
    if ($vd['zero'] != "Yes") {
        # If vat is not included (shipchrg)
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $shipchrg);
            $shipexvat = $shipchrg;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($shipchrg / ($VATP + 100) * $VATP);
            $shipexvat = $shipchrg - $scvat;
        } else {
            $scvat = 0;
            $shipexvat = $shipchrg;
        }
    } else {
        $scvat = 0;
        $shipexvat = $shipchrg;
    }
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn(PRD_DB);
    # get last ref number
    $refnum = getrefnum();
    db_connect();
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    $flag = TRUE;
    $checkid = 0;
    $nonstot = 0;
    foreach ($recvd as $sk => $keys) {
        if ($checkid == $ids[$keys]) {
            $flag = FALSE;
        } else {
            $flag = TRUE;
        }
        $checkid = $ids[$keys];
        # Skip zeros
        if ($qtys[$keys] <= 0) {
            continue;
        }
        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);
        if ($stk['units'] < 0) {
            $min_stock = abs($stk['units']);
            if ($qtys[$keys] < $min_stock) {
                $min_stock = $qtys[$keys];
            }
        } else {
            $min_stock = 0;
        }
        # Get selected stock line
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($pur['vatinc'] == "yes") {
            $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
        } else {
            $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']);
        }
        //$perc[$keys] = sprint((($unitcost[$keys]*$qtys[$keys])/$pur['subtot']) * 100);
        $perc[$keys] = sprint($unitcost[$keys] / $pur['subtot'] * 100);
        $ffs = $perc[$keys] * $qtys[$keys];
        # Get percentage from shipping charges excluding vat
        $shipc[$keys] = sprint($perc[$keys] / 100 * $shipexvat);
        //print "cost: percent:$ffs ship: part1".($unitcost[$keys]*$qtys[$keys])."part2".($shipc[$keys]*$qtys[$keys])."<br>";
        # add delivery charges = amt + del chrg excluding vat
        $unitcost[$keys] += $shipc[$keys];
        if ($stkd['udiscount'] > 0) {
            $discps = round($stkd['udiscount'] / 100 * $unitcost[$keys], 2);
        } else {
            $discps = 0;
        }
        $amt[$keys] = sprint($qtys[$keys] * $unitcost[$keys]);
        #serialized items are broken into multiples .... we only want to process the first ... so FLAG is used
        if (isset($invoice)) {
            $iq = $qtys[$keys];
            $iq += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($pur['vatinc'] == "yes") {
                $iamount = $stkd['amt'];
            } else {
                $iamount = sprint($stkd['amt'] + $stkd['svat']);
            }
            if ($flag) {
                vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
            }
            $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
            $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
        }
        $resub += $amt[$keys];
        # Update purchase items
        $sql = "\n\t\t\tUPDATE pur_items \n\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' \n\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        $cc = "";
        if ($stkd['account'] > 0) {
            if ($pur['vatinc'] == "yes") {
                #calculate the vat of this amount as we dont store it !!
                $vatcod = $stkd['vatcode'] + 0;
                $get_v = "SELECT vat_amount FROM vatcodes WHERE id = '{$vatcod}' LIMIT 1";
                $run_v = db_exec($get_v) or errDie("Unable to get vatcode information.");
                $varr = pg_fetch_array($run_v);
                $clearvat = $varr['vat_amount'] + 0;
                $remvat = sprint($stkd['amt'] / ($clearvat + 100) * $clearvat);
                $nonstot = $nonstot + $stkd['amt'] - $remvat;
            } else {
                $nonstot = $nonstot + $stkd['amt'];
            }
            $stk['whid'] = $stkd['account'];
            $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
            $banks = db_exec($sql);
            if (pg_numrows($banks) < 1) {
                return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
            }
            $barr = pg_fetch_array($banks);
            $bankid = $barr['bankid'];
            core_connect();
            $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
            # Check if link exists
            if (pg_numrows($rslt) < 1) {
                return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
            }
            $banklnk = pg_fetch_array($rslt);
            $cc_trantype = cc_TranTypeAcc($stkd['account'], $banklnk['accnum']);
        } else {
            # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if (isset($sers[$stkids[$keys]][$keys])) {
                ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $td);
                $serial = $sers[$stkids[$keys]][$keys];
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO pserec (\n\t\t\t\t\t\tpurid, purnum, stkid, serno, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
            }
            # Get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            //$sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}");
            db_connect();
            $cspric = sprint($amt[$keys] / $qtys[$keys]);
            $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t'{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Just wanted to fix the xxx.xxxxxxe-x value
            if ($stk['units'] > 0) {
                $csprice = round($stk['csamt'] / $stk['units'], 2);
            } else {
                $csprice = round($stk['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET csprice = '{$csprice}', lcsprice = '{$cspric}' \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        db_connect();
        # check if there are any outstanding items
        $sql = "SELECT * FROM pur_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 purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
        }
        if ($min_stock > 0) {
            $cost = sprint($unitcost[$keys] * $min_stock);
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            db_connect();
            $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'";
            $Ri = db_exec($Sl);
            writetrans($cosacc, $stockacc, $td, $refnum, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            db_connect();
            $Sl = "\n\t\t\t\tINSERT INTO pcost (\n\t\t\t\t\tpurnum, cost, qty, rqty, stkid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['purnum']}', '{$unitcost[$keys]}', '{$min_stock}', '0', '{$stk['stkid']}'\n\t\t\t\t)";
            $Ri = db_exec($Sl);
        }
    }
    //	$darr = explode ("-",$date);
    //	$cdate = "$darr[2]-$darr[1]-$darr[0]";
    #if non stock total is set, process the cost center
    if ($nonstot != "0") {
        $nonstot = sprint($nonstot);
        if ($cc_trantype != false) {
            $date = date("Y-m-d");
            $cc .= "\n\t\t\t\t<script>\n\t\t\t\t\tCostCenter('{$cc_trantype}', 'Non Stock Purchase', '{$date}', '{$stkd['description']}', {$nonstot}, '');\n\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
    }
    if (isset($invoice)) {
        ###################VAT CALCS#######################
        $pur['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['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($shipchrg, $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat_tmp = $vrs[0];
        $iamount_tmp = $vrs[1];
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$scvat);
        ####################################################
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$wh['conacc']}', '{$itotal}', \n\t\t\t\t'Stock Received - Purchase {$pur['purnum']} Inv:{$pur['supinv']}', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $isubtot, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Transfer vat
        writetrans($vatacc, $dept['credacc'], $td, $refnum, $ivat, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Ledger Records
        suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $itotal, 'c');
        db_connect();
        /* End Transactions */
        /* Make transaction record  for age analysis */
        db_connect();
        # update the supplier age analysis (make balance less)
        if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
            # Found? Make amount less
            $sql = "UPDATE suppurch SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        } else {
            /* Make transaction record for age analysis */
            $sql = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$itotal}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
        }
        /* Make transaction record  for age analysis */
        # commit updating
        $sql = "UPDATE purchases SET iamount = iamount+'{$itotal}',ivat=ivat+'{$ivat}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktRslt = db_exec($sql);
        $data = pg_fetch_array($stktRslt);
        $left = $data['sum'];
        if ($left == 0) {
            /* Start moving if purchase */
            if ($pur['received'] == "y") {
                if (strlen($pur['appdate']) < 8) {
                    $pur['appdate'] = date("Y-m-d");
                }
                # copy purchase
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, \n\t\t\t\t\t\tbalance, vatinc, vat, shipping, remarks, refno, received, done, \n\t\t\t\t\t\tdiv, purnum, supinv, ordernum, appname, appdate\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', \n\t\t\t\t\t\t'0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
                /*-- Cost varience -- */
                //$nsubtot = sprint($pur['total'] - $pur['vat']);
                $nsubtot = sprint($p['iamount'] - $p['ivat']);
                if ($p['rsubtot'] > $nsubtot) {
                    $diff = sprint($p['rsubtot'] - $nsubtot);
                    # Debit Stock Control and Credit Creditors control
                    writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
                } elseif ($nsubtot > $p['rsubtot']) {
                    $diff = sprint($nsubtot - $pur['rsubtot']);
                    # Debit Stock Control and Credit Creditors control
                    writetrans($cvacc, $wh['conacc'], $td, $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 pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $stktcRslt = db_exec($sql);
                while ($stktc = pg_fetch_array($stktcRslt)) {
                    # Insert purchase items
                    db_conn($pur['prd']);
                    $sql = "\n\t\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\t\tamt, svat, ddate, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
                # begin updating
                //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
                db_connect();
                # Remove the purchase from running DB
                $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                # Record where purchase is
                $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
                $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                # Remove those purchase items from running DB
                $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
                /* End moving purchase received */
                # commit updating
                //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
            } else {
                # insert Order to DB
                $sql = "UPDATE purchases SET invcd = 'y',supinv='{$pur['supinv']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
            }
        }
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    db_connect();
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    } else {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET part = 'y', rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    db_conn(PRD_DB);
    # get last ref number
    //$refnum = getrefnum();
    /* - Start Hooks - */
    /* - End Hooks - */
    # Record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        if (pg_num_rows($whRslt) < 1) {
            $sql = "SELECT stkacc,conacc FROM warehouses";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $wh['stkacc'] = $whid;
        } else {
            $wh = pg_fetch_array($whRslt);
        }
        # Debit Stock and Credit Stock control
        writetrans($wh['stkacc'], $wh['conacc'], $td, $refnum, $wamt, "Stock Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    # commit updating
    /*** pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    
    	/* Start moving if Order received and invoiced */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y" && $pur['invcd'] == 'y') {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, balance, \n\t\t\t\t\tvatinc, vat, shipping, remarks, refno, received, done, div, \n\t\t\t\t\tpurnum, supinv, ordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', \n\t\t\t\t\t'{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', \n\t\t\t\t\t'{$pur['purnum']}', '{$pur['supinv']}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $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 pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $cc .= "\n\t\t\t<script>\n\t\t\t\tprinter(\"" . SELF . "?key=recv_print&purid={$purid}\");\n\t\t\t</script>";
    }
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Order receipt 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='purchase-new.php'>New Purchase</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}