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

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

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

$col_of_yearfrom			= trim($_POST['year_from']);
$col_of_yearto				= trim($_POST['year_to']);
$col_of_year				= trim($_POST['year']);

$t2_name = '1_enumyears_'.date('dmy');
$coldefinitions = array();
$res = $DB->execute("describe {$col_to_match_t}");
if(!is_null($res)){
	$res = $res[0];
	while($W = $DB->nextRow($res)){
		$coldefinitions[$W['Field']] = $W['Type'];
	}
}
createTable($t2_name, $coldefinitions);

//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 />'YEAR ENUM' Started";
$res = $DB->execute("select * from {$col_to_match_t} group by ".toCSL($matches_1)." order by id ASC");
//echo "select * from {$col_to_match_t} group by ".toCSL($matches_1)." order by id ASC";
if(!is_null($res)){
	$res = $res[0]; $n = 0;
	while($W = $DB->nextRow($res)){
		$id = $W['id'];
		//for($i = 0; $i <= (2 + sizeof($W)/2); $i++){ unset($W[$i]); }
		for($i = 0; $i <= sizeof($W); $i++){ unset($W[$i]); }

		$yearfrom 	= (int) $W[$col_of_yearfrom];
		$yearto 	= (int) $W[$col_of_yearto];

		for($i = $yearfrom; $i <= $yearto; $i++){
			$n++;
			$W['id'] = $n;
			$W[$col_of_year] = $i;
			$DB->insert($W, $t2_name);
		}

		echo "<br />Done at #{$id}";
	}
	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;
}

function createTable($tblname, $coldefinitions){
	global $DB;	$sqlpart = "(";
	foreach($coldefinitions as $col => $definition){ $sqlpart .= "`{$col}` {$definition},"; }
	$sqlpart .= "PRIMARY KEY(id)) ENGINE=InnoDB";
	$DB->silentExecute("DROP TABLE IF EXISTS {$tblname}");
	if($DB->silentExecute("CREATE TABLE {$tblname} {$sqlpart}")) return true;
	else return false;
}
?>