set_time_limit(0);
global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
require_once DIR_WS_FUNCTIONS . 'html_output.php';
tep_db_connect();
$jng_sp_id = '5';
//NEW PROCESS WITH NEW CALC METHOD
use_class('jng_sp_orders');
$class_jo = new jng_sp_orders();
$orders_query = tep_db_query("SELECT jng_sp_orders_id FROM jng_sp_orders WHERE jng_sp_id={$jng_sp_id}");
$orders_count = 0;
while ($row = tep_db_fetch_array($orders_query)) {
    $orders_count++;
    $dataArray = $class_jo->calculateAnalysisData($row['jng_sp_orders_id']);
    $class_jo->saveAnalysisData($dataArray);
}
echo "{$orders_count} Order(s) are Processed";
echo '<br />';
//OLD PROCESS WITH OLD CALC METHOD
use_class('jng_sp_catalog');
$class_jc = new jng_sp_catalog();
$joi = array();
$joi_query = "SELECT joi.*";
$joi_query .= " FROM jng_sp_orders jo";
$joi_query .= " INNER JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_id=jo.jng_sp_orders_id";
$joi_query .= " WHERE jo.jng_sp_id={$jng_sp_id}";
$joi_result = tep_db_query($joi_query);
while ($row = tep_db_fetch_array($joi_result)) {
    if (!isset($joi[$row['products_id']])) {
/* RECALC VER. 2
 $q = "SELECT DISTINCT p.products_id FROM products p ";
$q .= " INNER JOIN products_use_elements pue ON pue.products_id = p.products_id AND pue.finishing_goldplate = '1'";
$q .= " WHERE p.products_status = 1";
$r = tep_db_query($q);
while($row=tep_db_fetch_array($r)) {
    $products_id = $row['products_id'];
    $class_pm->calculateMaterialExpenses($products_id);
    echo "update products $products_id<br/>";
    $products[] = $products_id;
}
echo count($products)." Products Mat. Exp. is updated<br/>";
die("DONE");
 */
//RECALC VC
$orders = array();
$q = "SELECT jng_sp_orders_id, jng_sp_orders_items_id, confirm_order_time, products_id, price, material_expenses";
$q .= " FROM jng_sp_orders_items";
$q .= " WHERE price / material_expenses < 0.5";
$q .= " ORDER BY jng_sp_orders_id DESC";
$r = tep_db_query($q);
while ($row = tep_db_fetch_array($r)) {
    $orders[] = $row['jng_sp_orders_id'];
}
tep_db_query("UPDATE jng_sp_orders_items SET material_expenses=0 WHERE jng_sp_orders_id IN (" . implode(',', $orders) . ")");
foreach ($orders as $order_id) {
    $dataArray = $class_jo->calculateAnalysisData($order_id);
    $class_jo->saveAnalysisData($dataArray);
}
echo count($orders) . " Order(s) are recalc";
tep_db_close();