<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT.'_class/createQuestion/Question.php');
include_once(PATH_TO_ROOT."_class/class.Extjs_tree.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."_support/class.UserSession.php");

	//the table for the project in DB_WARPIT_WEBCATI is named after the project name
	//the coresponding tree table has a _tree suffix
	$tableName = $db->get('_Projects',$_POST['id_project'],'proj_name',DB_WARPIT_WEBCATI_BASE);
	$tableNameTree = $tableName.'_tree';
	
	//let's check if the project has uniqueAddress field!
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$strucFields = $db->GetFields($tableName.'_structure');
	if(in_array('uniqueAddress_1', $strucFields) )
		$hasUnique = 1;
	else 
		$hasUnique = 0;
	
	//let's check if comment exists
	if(!in_array('mystery_comment',$strucFields))
	{
		$sql = "ALTER TABLE $tableName"."_structure ADD mystery_comment text";
		$db->SQLexecute($sql);
	}
		if(!in_array('mystery_image',$strucFields))
	{
		$sql = "ALTER TABLE $tableName"."_structure ADD mystery_image text";
		$db->SQLexecute($sql);
	}	
	$dataBase = DB_WARPIT_WEBCATI;
	$db->ChangeDatabase($dataBase );
	//let's create DA table if not exists!
	$sql = "CREATE TABLE IF NOT EXISTS $tableName"."_mystery (`id` INT NOT NULL AUTO_INCREMENT ,
`id_question` INT ,
`id_answer` INT ,
`id_legend` INT ,
`sc_value` FLOAT,
PRIMARY KEY (  `id` )
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
	$db->SQLexecute($sql);

	
	$projectId = $_POST['id_project'];
	$reqUrl = 'webcati/_forms/_ajax/ajax.statistics.php';
	//the tree on the left that has all the questions structured in fodlers
	$treeQ = new MakeTree($tableName.'_mystery_tree');
	//the table name is same as the project name
	//the special ajax manipulator takes care of geting the _tree table
	$treeQ->setMainTable($tableName,$dataBase);
	//for easier access to the tree name
	$treeName = $treeQ->getName();
	
	$treeQ->SetRootVisible("true","Questions")
		->addConfig('region',"'west'")

	//	->setLinesVisible(false)
		//->setBoldRoots()
		->setFontMedium()
		//we set the tree editable but the ajax manipulotar sets the leafs (questions) un-editable
		//so that only the groups are editable in the tree
		->setTextPadding('1px')
		->setSearchField('','top',100)
		->setWidth(180)
		->setReqUrl($reqUrl);
	//the SQL sentence to get the tree and additional data from the question table
	$treeQ->selectSQL = "SELECT {$tableName}_tree.*,$tableName.q_pos,$tableName.id as q_id ,tip_sql,hasStructure from {$tableName}_tree LEFT JOIN $tableName on id_question = $tableName.id";
	
	//creating the menu for selecting/deselecting question types
	?>
	var menu = new Ext.menu.Menu();
	menu.add(new Ext.menu.CheckItem({ 
	text:'Select all' 
	,hideOnClick:false //our menu won't close on click, so that we can check multiple 
	,handler:function(item) {
		var checked = ! item.checked; 
		var t = <?php echo $treeName ?>;
		item.parentMenu.items.each(function(i) {
		//we go through all children and check them  
		if(item !== i && i.setChecked && !i.disabled) { 
		i.setChecked(checked); 
		var chStr = 'checked['+i.qType+']';
		if(checked)
			{ //we add bgc classes and filter string to base params (so that we can dynamicly check newly loaded nodes
				i.addClass('x-check-item-bgc');
				t.getLoader().baseParams[chStr] = true;
			}
			else
			{
				i.removeClass('x-check-item-bgc');
				t.getLoader().baseParams[chStr] = false;
			}
		
		} 
		}); 
		t.getRootNode().cascade( //we cascade through the whole tree and check all nodes!!!
			function(n){
				if(n.attributes.isQuestion == true)
					n.getUI().toggleCheck(checked)
				
			}
			)
	} 
	}),'-');
	
	<?php 
	
	//we fetch all the questions in the database to create a menu item for it!
	$qRS = $db->SQLexecute("SELECT name,id FROM _QuestionTypes" );
	while ($qRow = $db->fetchArray($qRS)  )
	{
		$type = $qRow[1];
		$qTmp = Question::createQuestion( $qRow[1]  );
		//for each question we add a checkItem in the menu
		echo "menu.add(new Ext.menu.CheckItem( {text:'{$qRow[0]}' ,hideOnClick:false,qType:$type ,
		iconCls : '{$qTmp->getIconCls() }', //the icon covers the basic checkbox, so we added background coloring!!!
		handler:function(item){
			var checked = ! item.checked;
			if(checked)
			{	//if item is checked we add a bgc color and set the filter to true to check newly loaded nodes
				item.addClass('x-check-item-bgc');
				$treeName.getLoader().baseParams['checked[$type]'] = true;
			}
			else
			{	//if unchecked we remove bgc color and filter
				item.removeClass('x-check-item-bgc');
				$treeName.getLoader().baseParams['checked[$type]'] = false;
			}
				
			
			$treeName.getRootNode().cascade(
			function(n){ //we (un)check all nodes of the clicked type 
				if(n.attributes.qType == item.qType)
				{
					n.getUI().toggleCheck(checked)
				}
			}
			)
		}
	} ));";
	}
	
	
	$treeQ->addtBarItem("{ text:'Filter' 
,menu:menu }")
	->addConfig('enableDD','true')
	//we override the onInitDrag and disable node selection (this way our fields don't lose focus!)
	->addConfig('dragConfig',"{ /* onInitDrag : function(e){
        var data = this.dragData;
        //this.tree.getSelectionModel().select(data.node);
        this.tree.eventModel.disable();
        this.proxy.update(\"\");
        data.node.ui.appendDDGhost(this.proxy.ghost.dom);
        this.tree.fireEvent(\"startdrag\", this.tree, data.node, e);
    },*/ddGroup:'wcqbGroup' }  ");
	;
	
	
	
	//JS for the tree
	echo $treeQ->CreateTree();
	
	
	//we go through each children in the form and set a dropTarget with the group of the tree!


	
	
echo 	"

var recordCombo = new Ext.form.ComboBox({xtype:'combo',store: new Ext.data.JsonStore({
		url:'$reqUrl',
		baseParams : {
			action: 'userRecords',
			id_project: $projectId,
			flagbad:101
		},
		fields: ['id','name','flag_bad'],
		root:'rows'
	}),displayField:'name',valueField:'id',triggerAction:'all',mode:'local'
	  ,
		listeners:{
			'select': function(c,r){
				
			}
		}  });


var treeGrid_$tabId = new Ext.ux.tree.TreeGrid({
		 mysteryCheckBoxClick : function(val,ch)
{
	var bla = this.getNodeById(val);
	this.RMconn.request({
		params:{
			action: 'addScore',
			value: val,
			checked:ch,
			sc_value: bla.attributes.sc_value
		}
	});
},
	mysteryValEditClick: function(id,val)
	{
		var bla = this.getNodeById(id);
		bla.attributes.sc_value = val;
		this.RMconn.request({
		params:{
			action: 'addScval',
			value: id,
			scVal:val
		}
	});
	}
,
        id: 'treeGrid_$tabId',
    	closable:true,
    	region:'center',
    	enableSort:false,
        columns:[
       {
            header: 'Name / Label',
            dataIndex: 'q_name',
            width: 230
        }/*, {
        	header: 'Position',
        	width: 40,
        	dataIndex:'q_pos'
        }*/
        ,{
            header: 'Value',
            dataIndex: 'value',
            width:40
        },{
         header: 'Score',
            width: 100,
            dataIndex: 'score',
            align: 'center',  
            tpl: new Ext.XTemplate('<tpl if=\"leaf\"><input type=\"checkbox\" {score} onclick=\"Ext.getCmp(\'treeGrid_$tabId\'). mysteryCheckBoxClick(this.value,this.checked);\"  value=\"{id}\"></tpl>')
        },
        {
        	header:'Score value',
        	dataIndex: 'sc_value',
        	width:100,
        	type:'float',
        	tpl: new Ext.XTemplate('<tpl if=\"leaf\"><input type=\"textbox\" name={id} style=width:50; onchange=\"Ext.getCmp(\'treeGrid_$tabId\'). mysteryValEditClick(this.name,this.value);\" onclick=\" event.cancelBubble=true; \"  value=\"{sc_value}\"></tpl>')
 
        }
        ],
		tbar:[
		'User',{xtype:'combo',store: new Ext.data.JsonStore({
		url:'$reqUrl',
		baseParams : {
			action: 'compareUsers',
			id_project: $projectId,
			special:'Total report',
			hasUnique: $hasUnique,
			flagbad:101
		},
		fields: ['id','name'],
		autoLoad:true,root:'rows'
	}),
		listeners:{
			'select': function(c,r){
				
					recordCombo.setValue('');
					
				recordCombo.store.reload({
					params: {
						id_record: r.data.id
					}
				});
				
			},beforequery:function(qe){ delete qe.combo.lastQuery;}
		},displayField:'name',valueField:'id',triggerAction:'all' ,ref:'userCombo' }";
	if(!$hasUnique)
	echo ",' Record: ',
	recordCombo";
	echo ",
		
		{
			text:'Report',
			handler:function(){
			
			/*	mainTabPanel.add({
					xtype:'panel',
					title: 'Mystery report - $tableName',
					closable:true,
					html: '<iframe src=webcati/_forms/mysteryShopping/report.html.php?id_project=$projectId&id_record='+ recordCombo.getValue() + ' height=100% width=100% />'
				}).show();
			*/
			CallScript('webcati/_forms/mysteryShopping/forms.report.php',{ id_project:$projectId,id_record: $hasUnique ? treeGrid_$tabId.getTopToolbar().userCombo.getValue() : recordCombo.getValue() });
			}
		}],
        dataUrl: 'webcati/_forms/mysteryShopping/ajax.mysteryShopping.php',
        RMconn: new RMajax({
        	url:'webcati/_forms/mysteryShopping/ajax.mysteryShopping.php',
        	params:{database:'".$dataBase."',id_project:'$projectId' }
        })
            
    });
 
   treeGrid_$tabId.getRootNode().id = 0;
   treeGrid_$tabId.getLoader().baseParams = {action:'select',id_project:'$projectId'	
   };
     
  //let's destroy the menu!
	menu = null;
	var $tabId = new Ext.Panel({
		id:'$tabId',
		title:'Mystery shopping - $tableName',
		iconCls: 'icon_basic_statistics',
		closable:true,
		defaults:{split:true,border:false},
		layout:'border',
		border: false,
		items:[$treeQ ,treeGrid_$tabId
			
		 ]
		
	});
	";

	
	// write a name of a component, ExtJS evaluate this object into tree on the screen
	echo "mainTabPanel.add($tabId)";
	if(!$_POST['uniqueNotShow'])
		echo  ".show();";
//	echo 'buildQuestionnaire_'.$_POST['project'];	 

?>