<?php

include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");


$tabela = "`".DB_WARPIT_USERSPOOL."`._Recoder";


if ($_POST['action'] == 'delete' and $_POST['id']) {
	
	$sql = "DELETE FROM ".$tabela." WHERE id  = ".$_POST['id'];
	$db->SQLexecute($sql);
	
	echo "Ext.getCmp('".$_POST['gridID']."').getStore().reload();";
	
} elseif ($_POST['action'] == 'add') {
	

    $sql = "INSERT INTO  ".$tabela."  SET recode_condition = 'New condition', visible = 0";
	
	$db->SQLexecute($sql);
	echo "Ext.getCmp('".$_POST['gridID']."').getStore().reload();";
	exit;
	
} elseif ($_POST['action'] == 'update') {
	
	$sql = "UPDATE ".$tabela."  SET  ".$_POST['field']." = '".trim(addslashes($_POST['value']))."' WHERE id = ".$_POST['id'];
	$db->SQLexecute($sql);
	echo "{ success : true, sql: '".$sql."'}";

	
} elseif ($_POST['action'] == 'make-recode') {
	
	$sql = "SELECT recode_variable FROM ".$tabela." WHERE visible = 1 GROUP BY recode_variable";
	$res = $db->SQLexecute($sql);
	while ($zad = $db->fetchAssoc($res)) {
		$statVar[] 		= $zad['recode_variable'];
		$cleanVar[] 	= $zad['recode_variable']." = 0";
	}
	
	if ($cleanVar) {
		$sql = "UPDATE `".DB_WARPIT_USERSPOOL."`._Interviewer SET ".implode(",",$cleanVar);
		//echo $sql;
		$db->SQLexecute($sql);
	}
	
	$sql = "SELECT * FROM ".$tabela." WHERE visible = 1 ORDER BY orderBy";
	$res = $db->SQLexecute($sql);
	while ($zad = $db->fetchAssoc($res)) {
		$sql = "UPDATE `".DB_WARPIT_USERSPOOL."`._Interviewer 
					SET ".$zad['recode_variable']." = ".$zad['recode_value']." WHERE ".$zad['recode_condition'];
		$db->SQLexecute($sql);
		//echo $sql;
	}
	$vrni = "";
	if ($statVar) {
		foreach ($statVar as $sVar) { 
			$sql = "SELECT count(*) as n, ".$sVar." as v FROM `".DB_WARPIT_USERSPOOL."`._Interviewer GROUP BY ".$sVar;
			$res = $db->SQLexecute($sql);
			$vrni .= "<table border=1 cellpadding=5 cellspacing=0 style=\"padding:5px !important; width:180px\">";
			$vrni .= "<tr><td colspan=2>".$sVar."</td></tr>";
			while ($zad = $db->fetchAssoc($res)) $vrni .= "<tr><td>".$zad['v']."</td><td>".$zad['n']."</td></tr>";
			$vrni .= "</table>";
		}
	}
	$stat = "test
			 ca da
			 <table><tr>
			 	<td>trdsasdsa</td></tr></table>";
	echo " new Ext.Window({
                
                layout:'fit',
                title: 'Report',
                width:200,
                height: 300,
                closeAction:'close',
                plain: true,
                html : '".str_replace(array("\r\n", "\n", "\r"), '', $vrni)."' 
            }).show()";

	
} else {
	$data = array();
	
	$sql = "SELECT * FROM ".$tabela." ORDER BY visible,orderBy";
	//echo $sql;
	$result = $db->SQLexecute($sql);
	while ($dat = $db->fetchAssoc($result)) {
		$data[] = $dat;
	}
	echo "/*".$sql."*/";
	?>
	
	{
		success: true,
	    results: <?php echo sizeof($data);?>, 
	    rows: <?php echo json_encode($data); ?>        
	    
	}
<?php 
}
?>