<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");
include_once(PATH_TO_ROOT."webcati/_class/class.webrecode.statistics.php");
	
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

$idProject = $_POST['id_project'];
$layer = $_POST['layer'];
$projName = $_POST['projName'];

//echo "/*";
//print_r($fieldGroups);
//echo "*/";
//echo "console.log($numAll);";
//exit;
$cat=new MakeForm('sampler');
$cat->reqUrl='webcati/_forms/_ajax/ajax.quotas.php';
$cat->setTitle('Define');


//while(skozi vsa polja)
//$cat->addField('num','Number of samples:');
//$ cat->setTitle('Create category');
// ,callback:$this->buttonSendCallback
// element_values.getStore().reload();


$sql = "SELECT * FROM quota_layer WHERE layer = $layer ORDER BY zap_st";
$res = $db->SQLexecute($sql);
while ($row = $db->fetchAssoc($res))
{
	$src = $row['source'];
	$fieldMetaData[$row['q_name']] = $row;
	if($src == 3)
	{
		//GET ALL users
		$usersql =	"SELECT a.id_user,a.user_type,b.username FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids a INNER JOIN _Projects c ON a.id_project = c.id INNER JOIN (SELECT id as origId,username,password,Firstname,Surname,email,0 as id_type FROM ".DB_WARPIT_WEBCATI_BASE.".`_Interviewer` UNION SELECT id as origId,username,password,Firstname,Surname,email,1 as id_type FROM  ".DB_WARPIT_MAIN."._user) b ON a.id_user = b.origId AND a.user_type = b.id_type WHERE a.id_project = $idProject";
		$userRes = $db->SQLexecute($usersql);
		
		$pre = 'QU_';
		$fldArr = array();
		while ( $userRow = $db->fetchAssoc($userRes) )
		{
			$fldArr[] = $userRow['id_user'].'_'.$userRow['user_type'].' '.$userRow['username'];
		}
	}
	else
	{
		$sql = "SELECT id_reconum,rec_label FROM recolabel WHERE id_project = $idProject AND id_question = {$row['id_question']} AND source = {$row['source']} ORDER BY id_reconum";
		$fldRes = $db->SQLexecute($sql);
		$fldArr = array();
		while ($fldRow = $db->fetchAssoc($fldRes))
		{
			$fldArr[] = $fldRow['id_reconum'].' '.$fldRow['rec_label'];
		}
		if(!$fldArr && $src != 2)
		{
			//a telBase variable may not be recoded...then we use the base values and extract names
		}
		
		if($src == 2)
		{
			$pre = 'QT_';
		}
		else 
			$pre = 'TP_';
	}
	$fieldGroups[$pre.$row['q_name']] = $fldArr;
	
}

//let's get all defined values so that we can fill it up
$sql = "SELECT * FROM $projName"."___quotaLimits WHERE id_layer = $layer";
$res = $db->SQLexecute($sql);
while ($row = $db->fetchAssoc($res))
{
	$vals = array();
	foreach ($fieldGroups as $fldName => &$val) {
		if($fldName == "QU_user")
		{
			$vals[] = $row['QT_user_id'];
			$vals[] = $row['QT_user_type'];
		}
		else
			$vals[] = $row[$fldName];
	}
	$definedLimits[implode('_',$vals) ] = $row['q_value'];
	
}
$cat->addConfig('autoScroll','true')
->addConfig('labelWidth','300');

if($numAll <= 800)
		{	//we create up to 800 hundred (yes 800!!! some people are crazy) textfields with all possible combinations of ze layer!
			//$cat->addField('noMatter',implode(' ',array_keys($fieldGroups)),'label')->setProperty('labelWidth',500);
			
			
			$combTable .= "{autoScroll:true,html:";
			$htmlTable = "<table class=\"x-form-item x-form-item-label\" cellspacing=10>";
			$htmlTable .= '<tr><td>'.implode('</td><td>',array_keys($fieldGroups))."</td></tr>";
			$curNum = 0;
			function showCombinations($string, $traits, $i)
		    {
		    	global $curNum,$cat,$htmlTable,$labels,$definedLimits;
		        if ($i >= count($traits))
		        	{//the final combination
		            	$curNum++;
		            	
		            	$htmlTable .= '<tr><td>'.str_replace('|','</td><td>', $string ).'</td>';
		            	$htmlTable .= '<td><input type=text name="comboPodatki['.$string.']"';
						if(is_array($definedLimits))
						{
							foreach (explode('|',$string) as $val) {
								$val = explode(' ',$val);
								$values[] = $val[0];
							}
							$htmlTable .= "value=".$definedLimits[ implode('_',$values)  ];
							
						}
		            	$htmlTable .= ' /></td></tr>';
		            //	$cat->addField('combination_'.$curNum,$string,'textfield');
		            	
		        	}
		        else
		        {
		        	//we have to find the element on index $i!
		        	$c = 0;
		        	foreach ($traits as $fld=>$test)
		        	{
		        		if($c == $i) break;
		        		$c++;
		        	}
		        	
		            foreach ($test as $trait)
		            {	
		            //	if($labels[$fld][$trait] )
		            //		$trait .= ' '.$labels[$fld][$trait];
		                showCombinations($string ? $string.'|'. $trait : $trait , $traits, $i + 1);
		            }
		        }
		    }
		    showCombinations('', $fieldGroups, 0);
			$htmlTable .= "</table>";
			$combTable .= json_encode($htmlTable)."}";
			//in this case OK button simply submits!
			$addButtonFunc = "function(){
 " . $cat->getName() . ".getForm().submit({timeout : 100000,params: {fields:'".implode(',',array_keys($fieldGroups))."'  ,
 id_project:".$idProject.", grid_action:'insert_layer_define',layerId:$layer },
  success:function(){win111111111.close();Ext.getCmp('{$projName}_quota_layers').getStore().reload(); } }); }";
  	$fbarExtra = "'Set all: ', {xtype:'numberfield',fieldLabel:'Set all',width:80 },{xtype:'button',text:'Load',handler:function(){
  		var fr = $cat.form.el.dom; 
  		var val = $cat.fbar.items.items[1].value;
  		if(val)
		for(var i=0;i<fr.length;i++)
		{
			fr[i].value = val;
		}
		}},";
		}
else //otherwise we create a grid, where the user can select the sample data and add a values
{
	$grid = new MakeGrid();
	$grid->dataArray = '[[]]';
	$grid->addConfig('autoHeight','true')->addConfig('clicksToEdit',1);
	$grid->setEditable(false);
	$grid->listeners[] = "afteredit:function(e){
	e.record.commit();
	if(e.row + 1 == $grid.getStore().getCount())
	{
		var recGood = true;
		for(prop in e.record.data)
		{
			if(!e.record.data[prop]) recGood = false;
		}
		if(recGood) $grid.getStore().loadData([[]],true);
	}
}";
	foreach ($fieldGroups as $fieldName => $groups) {
		$grid->addColumn($fieldName,$fieldName)->type('combo')->comboStore( $groups );
	}
	$grid->addColumn('samples','Samples',"new Ext.form.NumberField()");
	echo $grid->createGrid();
	$cat->addItem($grid);
	//the OK button must create parameters from grid to send!
	$addButtonFunc = "function(){
	var par = {};
	$grid.getStore().each(function(rec){
		var recGood = true;
		for(prop in rec.data)
		{
			if(!rec.data[prop]) recGood = false;
		}
		if(!recGood) return true;
		var poop = new Array();";
	foreach ($fieldGroups as $fld => &$nan) {
		$addButtonFunc .= "poop.push(rec.data['$fld']);\n";
	}
	$addButtonFunc .= "
	par['comboPodatki['+poop.join('|')+']'] = rec.data.samples;
	});
 " . $cat->getName() . ".getForm().submit({timeout : 100000,params: Ext.apply(par,{fields:'".implode(',',array_keys($fieldGroups))."'  ,id_project:".$idProject.",
  grid_action:'insert_layer_define',layerId:$layer}),
  success:function(){//win111111111.close();
} }); }";
}
$cat->addItem($combTable);
/*$cat->addButton("Ok",$addButtonFunc);
$cat->addButton("Cancel","function(){ win111111111.close(); }");*/
$cat->addConfig('fbar',"[$fbarExtra {xtype:'button',text:'Ok',handler:$addButtonFunc},{xtype:'button',text:'Cancel',handler:function(){ win111111111.close(); }}]");
$cat->addConfig('closable',"false");

echo $cat->createForm();


$importTab = new MakeForm('importTab');
$importTab->reqUrl='webcati/_forms/_ajax/ajax.quotas.php';
$importTab->setTitle('Import');
$importTab->addField(array(
    'xtype' => 'fileuploadfield',
    'readOnly' => "true",
    'name' => 'importData',
    'anchor' => '95%',
    'fieldLabel' => 'Select file',
    'buttonText' => "''",
    'buttonCfg' => '{
        iconCls: "upload-icon"
    }'
));
$importTab->addConfig('enctype',"'multipart/form-data'");
$importTab->addConfig('closable',"false");
$importTab->addConfig('fileUpload', "true");
$importTab->addConfig('fbar', "[
{
    xtype: 'button',
    text: 'Import',
    handler: function()
    {
        $importTab.getForm().submit({
            params:{
                action: 'uploadQuotas'
            },
            success: function(cmp, resp){
                var data = Ext.decode(resp.response.responseText).data;
                var fr = $cat.form.el.dom;
                 
                for(var i=0;i<data.length;i++)
                        fr[i].value = data[i];
                 
                $importTab.getForm().reset(); 
                Ext.getCmp('quota_define_window_tab').setActiveTab(0);
            }
        });
    }
}
]");


echo $importTab->createForm();

?>



var win111111111 = new Ext.Window({
        id:'win111111111',
 		title: 'Define layer',
        layout:'fit',
        width:600,
        height:600,
        autoScroll:true,
        closeAction:'close',
        plain: true,
        items: [
        {
            id:'quota_define_window_tab',
            xtype: 'tabpanel',
            items: [sampler, importTab]
        }
		],
		modal: true
    }).show();
    
Ext.getCmp('quota_define_window_tab').setActiveTab(0);
