function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return edit($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($whid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($unitnum, "num", 1, 50, "Invalid number of units.");
    $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit.");
    $v->isOk($cacc, "num", 1, 50, "Invalid contra account.");
    $v->isOk($tipo, "string", 1, 50, "Invalid type.");
    $v->isOk($det, "string", 0, 255, "Invalid Details.");
    $v->isOk($date, "string", 4, 14, "Invalid date.");
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk("##", "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    if ($stk['units'] < 0) {
        $min_stock = abs($stk['units']);
        if ($unitnum < $min_stock) {
            $min_stock = $unitnum;
        }
    } else {
        $min_stock = 0;
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $refnum = getrefnum();
    # calculate actual cost amount
    $temp = $cost;
    $cost = sprint($cost * $unitnum);
    if ($tipo == 'Increase') {
        # Update Stock
        db_connect();
        $sql = "UPDATE stock\n\t\t\t\tSET units = (units + '{$unitnum}'),\n\t\t\t\t\tlcsprice = '{$temp}',\n\t\t\t\t\tcsamt = (csamt + {$cost}),\n\t\t\t\t\tcsprice = (\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tCASE WHEN (units != -{$unitnum}) THEN (csamt+{$cost})/(units+{$unitnum})\n\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\tEND\n\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\tWHERE stkid='{$stkid}' AND div='" . USER_DIV . "'\n\t\t\t\t\t)\n\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        //		$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
        $sdate = $date;
        recordtrans('stock', '1', '1', $sdate, $unitnum, $cost, $temp, '', $stkid);
        db_connect();
        if ($unitnum == 0) {
            $csprice = 0;
        } else {
            $csprice = sprint($cost / $unitnum);
        }
        recordtrans('stock', '1', '0', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $det);
        $sql = "INSERT INTO stockrec (edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')";
        //		$recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID.";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        # balance transaction
        # Debit STock account and Credit Contra Account
        recordtrans('journal', $wh['stkacc'], $cacc, $date, $refnum, $cost, '0', $det);
        //writetrans($wh['stkacc'], $cacc, $date, $refnum, $cost, $det);
        $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $cacc);
    } else {
        if ($tipo == 'Decrease') {
            # Update Stock
            db_connect();
            $sql = "UPDATE stock SET csamt = (csamt - {$cost}), units = (units - '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            //		$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            //$sdate = date("Y-m-d");
            $sdate = $date;
            recordtrans('stock', '0', '0', $sdate, $unitnum, $cost, '0', $det, $stkid);
            recordtrans('stock', '0', '1', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']);
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $unitnum, $cost, $det);
            db_connect();
            if ($unitnum == 0) {
                $csprice = 0;
            } else {
                $csprice = sprint($cost / $unitnum);
            }
            $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')";
            //$recRslt = db_exec($sql);
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($stkRslt) < 1) {
                return "<li> Invalid Stock ID.</li>";
            } else {
                $stk = pg_fetch_array($stkRslt);
            }
            # Units
            if ($stk['units'] != 0) {
                $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                //			$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            } else {
                $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                //			$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            }
            if (isset($sernos)) {
                foreach ($sernos as $skey => $serno) {
                    ext_OutSer($serno, $stkid, $det, $refnum, "tran");
                }
            }
            recordtrans('journal', $cacc, $wh['stkacc'], $date, $refnum, $cost, '0', $det);
            #  Debit Contra Account and Credit Stock account
            //writetrans($cacc, $wh['stkacc'], $date, $refnum, $cost, $det);
            $cc_trantype = cc_TranTypeAcc($cacc, $wh['stkacc']);
        }
    }
    if ($cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Stock Transaction', '{$date}', '{$det}', '{$cost}', ''); </script>";
    } else {
        $cc = "";
    }
    $write = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Stock Balance Transaction</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Stock Balance Transaction for stock, {$stk['stkdes']} ({$stk['stkcod']}) has been successfully recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("stock-add.php", "Add Stock"), ql("stock-view.php", "View Stock"));
    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);
    if (isset($back)) {
        return edit($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($unitnum, "float", 1, 50, "Invalid number of units.");
    $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit.");
    $v->isOk($det, "string", 0, 255, "Invalid Details.");
    $v->isOk($date, "string", 4, 14, "Invalid date.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $refnum = getrefnum();
    /*refnum*/
    # calculate actual cost amount
    $cost = sprint($cost * $unitnum);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $banklnk = pg_fetch_array($rslt);
    $cacc = $banklnk['accnum'];
    ############## PROCESS VAT + AMOUNTS ################
    $totamt = $cost;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $vd = pg_fetch_array($Ri);
    $vatp = $vd['vat_amount'];
    if ($chrgvat == "exc") {
        $totamt += $vat;
    } elseif ($chrgvat == "inc") {
        $cost = sprint($totamt - $vat);
    } else {
        //		$vat = "No VAT";
    }
    ################# DONE ###################
    pglib_transaction("BEGIN");
    if ($ttype == 'payment') {
        # Update Stock
        db_connect();
        $sql = "UPDATE stock SET csamt = (csamt + '{$cost}'), units = (units + '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        $sdate = $date;
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $det);
        db_connect();
        $cspric = sprint($cost / $unitnum);
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div\n\t\t\t) VALUES (\n\t\t\t\t'{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$unitnum}', '{$cost}', '{$cspric}', '{$det}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID.</li>";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        # Units
        if ($stk['units'] != 0) {
            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        } else {
            $csprice = sprint($cost / $unitnum);
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        }
        /*		$totamt = $cost;
        
        		db_conn('cubit');
        
        		$Sl="SELECT * FROM vatcodes WHERE id='$vatcode'";
        		$Ri=db_exec($Sl) or errDie("Unable to get vat codes");
        		$vd=pg_fetch_array($Ri);
        		$vatp = $vd['vat_amount'];
        		if($chrgvat == "exc"){
        		$totamt += $vat;
        		} elseif($chrgvat == "inc"){
        		$cost=sprint($totamt-$vat);
        		}else{
        		$vat = "No VAT";
        		}*/
        # Debit STock account and Credit Contra Account
        writetrans($wh['stkacc'], $cacc, $date, $refnum, $cost, $det);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $det);
        }
        vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, $det, -($cost + $vat), -$vat);
        $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $cacc);
        $temp = $cost + $vat;
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, \n\t\t\t\tdiv, vatcode, stkinfo\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$det}', '{$det}', '0', '{$temp}', '{$vat}', '{$chrgvat}', 'no', '{$wh['stkacc']}', \n\t\t\t\t'" . USER_DIV . "', '{$vatcode}', '{$stk['stkid']}|{$unitnum}|{$cost}|{$vat}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    } elseif ($ttype == 'receipt') {
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
        # Update Stock
        db_connect();
        $sql = "UPDATE stock SET csamt = (csamt - {$cost}), units = (units - '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        $sdate = $date;
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $unitnum, $cost, $det);
        db_connect();
        $cspric = sprint($cost / $unitnum);
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div\n\t\t\t) VALUES (\n\t\t\t\t'{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$unitnum}', '{$cost}', '{$cspric}', '{$det}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID. </li>";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        if ($stk['units'] != 0) {
            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        } else {
            $csprice = sprint($cost / $unitnum);
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        }
        if (isset($sernos)) {
            foreach ($sernos as $skey => $serno) {
                // ext_invSer($serno, $stkid);
                ext_OutSer($serno, $stkid, $det, $refnum, "tran");
            }
        }
        #  Debit Contra Account and Credit Stock account
        writetrans($cacc, $wh['stkacc'], $date, $refnum, $cost, $det);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $det);
        }
        vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, $det, -($cost + $vat), -$vat);
        $cc_trantype = cc_TranTypeAcc($cacc, $wh['stkacc']);
        $temp = $cost + $vat;
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, \n\t\t\t\tstkinfo\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'deposit', '{$date}', '{$det}', '{$det}', '0', '{$temp}', '0', 'no', 'no', '{$wh['stkacc']}', '" . USER_DIV . "','1',\n\t\t\t\t'{$stk['stkid']}|{$unitnum}|{$cost}|{$vat}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    }
    pglib_transaction("COMMIT");
    // Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Stock Bank Transaction</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Stock Bank Transaction for: {$stk['stkdes']} ({$stk['stkcod']}) has been successfully recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='../stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='../stock-view.php'>View Stock</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;
}