<?php require_once("../../classes/DBConnection.php"); $DB = new DBConnection();

$col_to_match_t 			= trim($_POST['col_to_match_t']);

$cols_to_match				= explode(',',trim($_POST['col_to_match']));

$col_to_focus_on_t			= trim($_POST['col_to_focus_on_t']);
$col_to_focus_on_for_min 	= trim($_POST['col_to_focus_on_for_min']);
$col_to_focus_on_for_max 	= trim($_POST['col_to_focus_on_for_max']);
$col_to_update_t 			= trim($_POST['col_to_update_t']);
$col_to_update_with_min 	= trim($_POST['col_to_update_with_min']);
$col_to_update_with_max 	= trim($_POST['col_to_update_with_max']);

//Clean up strings
$matches_1 = array();
$matches_1_val = array();
foreach($cols_to_match as $m){
	$m = trim($m); if($m=="") continue;
	$matches_1[] = $m;
}

echo "<br />'MIN and MAX' Started";
$res = $DB->execute("select ".toCSL($matches_1).", id from {$col_to_match_t} group by ".toCSL($matches_1)." order by id ASC");
if(!is_null($res)){
	$res = $res[0];
	while($W = $DB->nextRow($res)){
		$id = $W['id'];

		for($i=0; $i<sizeof($matches_1); $i++){
			$matches_1_val[$i] = trim($W[$matches_1[$i]]);
		}
		
		$R = $DB->execute("select MIN({$col_to_focus_on_for_min}) as minv, MAX({$col_to_focus_on_for_max}) as maxv from {$col_to_focus_on_t} where ".andCondition($matches_1, $matches_1_val)." and {$col_to_focus_on_for_min}>0");

		if(!is_null($R)){
			$R = $R[0];
			$Y = $DB->nextRow($R);
			$minv = $Y['minv'];
			$maxv = $Y['maxv'];
			if($DB->simpleQuery("update {$col_to_update_t} set {$col_to_update_with_min} = '{$minv}', {$col_to_update_with_max} = '{$maxv}' where ".andCondition($matches_1, $matches_1_val))){
				echo "<br />Done at #{$id}";
			}else{
				echo "<br /><span style='color:#F00'>Error at #{$id}</span>";
			}
		}
	}
	echo "<br />ENDED<hr />";
}else{ "<span style='color:#F00'>Error in operation</span><br />"; }

function andCondition($names, $values){
	global $DB;
	$cond = "";
	for($i=0; $i<sizeof($names); $i++){
		//$cond .= " and `{$names[$i]}`='".$DB->escape_string($values[$i])."'";
		$cond .= " and `{$names[$i]}` like '".$DB->escape_string($values[$i])."%'";
	}
	$cond = substr($cond, 5);
	return $cond;
}

function toCSL($arr){
	global $DB;
	$ret = "";
	foreach($arr as $a){ $ret .= ",`".$DB->escape_string($a)."`"; }
	$ret = substr($ret,1);
	return $ret;
}
?>