<?
//return;

require_once("modules/EcmStockStates/EcmStockState.php");
$ss=new EcmStockState();
set_time_limit(1000000);
//error_reporting(E_ALL);

$sarr=array();
$parr=array();

//  https://crm.e5.pl/index.php?module=EcmStockStates&action=rebuildStates&ids=20e88740-56f6-7306-1008-647450c5e4fd,d783e0de-2ea0-f783-d29b-5bffea73981c

if (isset($_GET['ids'])) {
	$ids = explode(',', $_GET['ids']);
	$w=$GLOBALS['db']->query("SELECT so.stock_id, so.product_id FROM ecmstockoperations AS so
		INNER JOIN ecmproducts AS p ON p.id = so.product_id
		WHERE p.id IN ('".implode("','", $ids)."')
		ORDER BY so.date_entered");
} else if (isset($_GET['codes'])) {
	$codes = explode(',', $_GET['codes']);
	$w=$GLOBALS['db']->query("SELECT so.stock_id, so.product_id FROM ecmstockoperations AS so
		INNER JOIN ecmproducts AS p ON p.id = so.product_id
		WHERE p.code IN ('".implode("','", $codes)."')
		ORDER BY so.date_entered");
} else {
	$w=$GLOBALS['db']->query("
		select stock_id, product_id from ecmstockoperations 
		order by date_entered");
}


while($r=$GLOBALS['db']->fetchByAssoc($w)){
	if(!in_array($r['stock_id'],$sarr))$sarr[]=$r['stock_id'];
	if(!in_array($r['product_id'],$parr))$parr[]=$r['product_id'];

	brecho($r['stock_id'],$r['product_id']);
}

for($i=0;$i<count($parr);$i++){
	for($j=0;$j<count($sarr);$j++){
		if($parr[$j] && $sarr[$j])$ss->UpdateStockState($sarr[$j],$parr[$i]);
	}
}

function brecho() {
	echo '<pre>';
	foreach(func_get_args() as $obj) {
		print_r($obj);
		echo "<br>";
	}
	echo '</pre>';
}
?>