function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get 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>- 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>";
    }
    //	$td = $pur['pdate'];
    $td = "{$p_year}-{$p_month}-{$p_day}";
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : Purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department 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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stktRslt)) {
        $iq = $qty[$stkd['id']];
        $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']);
        }
        //$pur['pdate'] -> $td
        vatr($vd['id'], $td, "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.");
    }
    ###################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($pur['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), -$ivat_tmp);
    ####################################################
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$TOTAL}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    //$pur['pdate'] -> $td
    $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, \n\t\t\t\tref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$td}', '{$wh['conacc']}', '{$TOTAL}', 'Stock Received - Purchase {$pur['purnum']} Inv:{$supinv}', \n\t\t\t\t'{$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, sprint($SUBTOT + $del), "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $VAT, "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.", $TOTAL, 'c');
    /* 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 = "\n\t\t\t\t\tUPDATE suppurch \n\t\t\t\t\tSET balance = (balance + '{$TOTAL}') \n\t\t\t\t\tWHERE 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 {
        //$pur['pdate'] -> $td
        /* 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']}', '{$td}', '{$TOTAL}', '" . 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+'{$TOTAL}',ivat=ivat+'{$VAT}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    $p = pg_fetch_array($purRslt);
    //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",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']);
            //$pur['pdate'] -> $td
            $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, terms, \n\t\t\t\t\tpdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tshipping, remarks, refno, received, done, div, purnum, supinv, \n\t\t\t\t\tordernum, 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']}', '{$pur['terms']}', \n\t\t\t\t\t'{$td}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', \n\t\t\t\t\t'{$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']);
            $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)) {
                db_conn($pur['prd']);
                $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);
            }
            # 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='{$supinv}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        }
    }
    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>Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$pur['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
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # 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>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class=err> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.";
        $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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($sql);
    $refnum = getrefnum();
    while ($id = pg_fetch_array($Ri)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$id['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($id['svat'] == 0) {
            $exvat = "y";
        } else {
            $exvat = "";
        }
        $vr = pvatcalc($id['amt'], $pur['vatinc'], $exvat);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Purchase {$pur['purnum']} Supplier : {$pur['supname']}.", $iamount, $ivat);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}', '{$pur['total']}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "')";
    $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, $pur['total'] - $pur['vat'], "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $pur['vat'], "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.", $pur['total'], '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 + '{$pur['total']}') 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 = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$pur['total']}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    //1 ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Start moving if purchase */
    if ($pur['received'] == "y") {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv,ordernum,appname,appdate)";
        $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['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$supinv}','{$pur['ordernum']}','{$pur['appname']}','{$pur['appdate']}')";
        $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 = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, svat, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        # begin updating
        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
    } else {
        # insert Order to DB
        $sql = "UPDATE purchases SET invcd = 'y',supinv='{$supinv}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Purchase Invoiced</th></tr>\n\t\t<tr class='bg-even'><td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='purchase-view.php'>View purchases</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # 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($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($subtot, "float", 1, 20, "Invalid Sub Total.");
    $v->isOk($shipping, "float", 1, 20, "Invalid Delivery Charges.");
    $v->isOk($vat, "float", 1, 20, "Invalid VAT");
    $v->isOk($total, "float", 1, 20, "Invalid Total");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get 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>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase 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);
    }
    $sdate = date("Y-m-d");
    $date = $pur["pdate"];
    $refnum = getrefnum();
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $subtot = sprint($subtot);
    $shipping = sprint($shipping);
    $vat = sprint($vat);
    $total = sprint($total);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        $cqty = $stkt['qty'] - $stkt['rqty'];
        # update stock(ordered - qty)
        $sql = "UPDATE stock SET ordered = (ordered - '{$cqty}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$total}') 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']}', '{$date}', '{$dept['credacc']}', '{$total}', 'Stock Received - Purchase {$pur['purnum']}', '{$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'], $date, $refnum, $total - $vat, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $date, $refnum, $vat, "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $date, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $total, '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 + '{$total}') 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 = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$date}', '{$total}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if purchase */
    # copy purchase
    db_conn($pur['prd']);
    $sql = "\n\t\tINSERT INTO purchases (\n\t\t\tpurid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv\n\t\t) VALUES (\n\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$subtot}', '{$total}', '0', '{$pur['vatinc']}', '{$vat}', '{$shipping}', '{$remarks}', '{$refno}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$pur['supinv']}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Purchase to Cubit.", SELF);
    /*-- Cost varience -- */
    $nsubtot = $total - $vat;
    if ($pur['rsubtot'] > $nsubtot) {
        $diff = $pur['rsubtot'] - $nsubtot;
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $date, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($nsubtot > $pur['rsubtot']) {
        $diff = $nsubtot - $pur['rsubtot'];
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $date, $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 (rqty) > 0 AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        $stktc['amt'] = $stktc['unitcost'] * $stktc['rqty'];
        # Insert purchase items
        db_conn($pur['prd']);
        $sql = "\n\t\t\tINSERT INTO pur_items (\n\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, amt, ddate, div, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['rqty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "', '{$stktc['vatcode']}'\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert purchase 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);
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Completed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase receipt from Supplier <b>{$pur['supname']}</b> has been completed.</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);
    # 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.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid Subtotal.");
    foreach ($rvat as $rvat_k => $rvat_v) {
        $v->isOk($rvat_v, "float", 0, 40, "Invalid vat ({$rvat_v}).");
    }
    $v->isOk($total, "float", 1, 20, "Invalid total.");
    # Used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get 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 purchase has been received
    if ($pur['received'] == "n") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</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");
    $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();
    $d = date("Y-m-d");
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn('cubit');
    $Sl = "INSERT INTO dnotes (purid,date,sub,vat,tot) VALUES ('{$purid}','{$d}','{$subtot}','{$vat}','{$total}')";
    $Ri = db_exec($Sl) or errDie("Unable insert data.");
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purchases SET noted = 'y', rsubtot = 0, remarks = '{$remarks}' WHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    /* - Start Hooks - */
    $refnum = getrefnum();
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    $retot = sprint($subtot + $vat);
    $sdate = $pdate;
    //date("Y-m-d");
    # Debit Supplier control, credit inv control
    //	writetrans($dept['credacc'], $vatacc, date("d-m-Y"), $refnum, $vat, "Credit Note for VAT return on Purchase No. $pur[purnum] from Supplier : $sup[supname].");
    //	writetrans($dept['credacc'], $wh['conacc'], date("d-m-Y"), $refnum, $subtot, "Credit Note for Stock return on Purchase No. $pur[purnum] from Supplier : $sup[supname].");
    writetrans($dept['credacc'], $vatacc, $pur['pdate'], $refnum, $vat, "Credit Note for VAT return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    writetrans($dept['credacc'], $wh['conacc'], $pur['pdate'], $refnum, $subtot, "Credit Note for Stock return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl);
    $f = 0;
    while ($vd = pg_fetch_array($Ri)) {
        $vid = $vd['id'];
        if ($rvat[$vid] < 0.01) {
            continue;
        }
        if ($f == 0) {
            $AM = sprint($subtot + $vat);
        } else {
            $AM = 0;
        }
        //$vd.="<tr><td><input type=hidden name='rvat[$vid]' value='$rvat[$vid]'></td></tr>";
        vatr($vd['id'], date("Y-m-d"), "INPUT", $vd['code'], $refnum, "Return VAT for Purchase No. {$pur['purnum']}", $AM, $rvat[$vid]);
        $f++;
    }
    db_connect();
    # Update the supplier (make balance less)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "\n\t\t\t\tUPDATE suppurch \n\t\t\t\tSET balance = (balance - '{$retot}') \n\t\t\t\tWHERE 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\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pdate}', '-{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    # Remove all empty entries
    $sql = "DELETE FROM suppurch WHERE balance = 0::numeric(13,2) AND fbalance = 0::numeric(13,2) AND div = '" . USER_DIV . "'";
    $rs = db_exec($sql);
    $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']}', '{$pdate}', '{$dept['credacc']}', '-{$retot}', 'Stock Returned', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $sdate, $pur['purid'], "Stock Purchase No. {$pur['purnum']} returned.", $retot, 'd');
    /*-- Cost varience -- */
    if ($pur['rsubtot'] > $subtot) {
        $diff = sprint($pur['rsubtot'] - $subtot);
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $sdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($subtot > $pur['rsubtot']) {
        $diff = sprint($subtot - $pur['rsubtot']);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $sdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    /*-- End Cost varience -- */
    /* End Transactions */
    db_conn($prd);
    $sql = "UPDATE pur_items SET ctqty = '0' WHERE purid = '{$purid}' AND ctqty > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # 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 Credit Note</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock Return Credit note 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-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);
    # 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.");
    // $v->isOk ($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid Subtotal.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($total, "float", 1, 20, "Invalid total.");
    # 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);
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Update purchase on the DB
    db_conn($prd);
    $sql = "UPDATE purch_int SET noted = 'y', rsubtot = 0, rtax = 0, remarks = '{$remarks}' WHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    /* - Start Hooks - */
    $refnum = getrefnum();
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    $retot = sprint($subtot + $tax);
    $sdate = date("Y-m-d");
    $lsubtot = sprint($subtot * $pur['xrate']);
    $ltax = sprint($tax * $pur['xrate']);
    $lretot = sprint($retot * $pur['xrate']);
    # Debit Supplier control, credit inv control
    //date("d-m-Y")
    writetrans($dept['credacc'], $vatacc, $pdate, $refnum, $ltax, "Credit Note for Vat return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    writetrans($dept['credacc'], $wh['conacc'], $pdate, $refnum, $lsubtot, "Credit Note for Stock return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    db_connect();
    # update the supplier (make balance less)
    $sql = "UPDATE suppliers SET fbalance = (fbalance - '{$retot}'), balance = (balance - '{$lretot}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # 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 fbalance = (fbalance - '{$retot}'), balance = (balance - '{$lretot}') 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 = "INSERT INTO suppurch(supid, purid, pdate, balance, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$sdate}', '-{$lretot}', '-{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    $Date = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$Date}', '{$dept['credacc']}', '-{$retot}', 'Stock Returned', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $Date, $pur['purid'], "Stock Purchase No. {$pur['purnum']} returned.", $lretot, 'd');
    /*-- Cost varience -- */
    //date("d-m-Y")
    if ($pur['rsubtot'] > $subtot) {
        $diff = sprint($pur['rsubtot'] - $subtot);
        # Debit Stock Control and Credit Creditors control
        writetrans($cvacc, $wh['conacc'], $pdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    } elseif ($subtot > $pur['rsubtot']) {
        $diff = sprint($subtot - $pur['rsubtot']);
        # Debit Stock Control and Credit Creditors control
        writetrans($wh['conacc'], $cvacc, $pdate, $refnum, $diff, "Cost Variance for Stock Return on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    /*-- End Cost varience -- */
    /* End Transactions */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Stock Return</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Stock Return to Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
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;
}
 function is_localb($table, $key, $val)
 {
     db_connect();
     return ext_ex2($table, $key, $val, "btype", "loc");
 }