<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");


	$tableName = '_Interviewer';
	
	
	$isWebcati = $_POST['userGroup'] == 'webcati';
	if($isWebcati)
	{
		$database = DB_WARPIT_WEBCATI_BASE;
		$grpTree = 'CatiMenu';
	}
	else
	{
		$database = DB_WARPIT_USERSPOOL;
		$grpTree = 'PoolMenu_1';
	}
	
	$tabId = $_POST['uniqueTabId'];
	//this form can be used to show users from different conditions
	/**
	 * showType = 0 - show users from a selected group (double click on group)
	 * showType = 1 - show all users in _Interviewer table (double click on root in groups tree)
	 * showType = 2 - show users that meet the conditions in a sql query template!
	 */
	if(isset($_POST['group_id']))
	{
		//groups
		$groupId = $_POST['group_id'];
		//we filter the users by the group
		$baseParams = 'group_id:'.$_POST['group_id'];
		$title = 'Group';
		$icon = 'icon_userspool_group';
		if($_POST['group_id'] != 0 )
		{ $showType = 0;
			if($isWebcati)
				$selectSQL = 'SELECT a.* from '.DB_WARPIT_WEBCATI_BASE.'._group_link b INNER JOIN '.
						"(SELECT id,id as origId,username,password,Firstname,Surname,0 as id_type FROM ".DB_WARPIT_WEBCATI_BASE.".`_Interviewer` UNION SELECT CONCAT('admin_',id) as id,id as origId,username,password,Firstname,Surname,1 as id_type FROM  ".DB_WARPIT_MAIN."._user) a"
				.' ON b.id = a.origId AND b.id_type = a.id_type';
			else
				$selectSQL = 'SELECT a.* from _group_link b INNER JOIN _Interviewer a ON a.id = b.id';// WHERE b.id_group = '.$_POST['group_id'];
		}
		else 
		{ 
			//groups All!
			$showType = 1;
			//$selectSQL = 'SELECT * from _Interviewer';
			if($isWebcati)
				$selectSQL = 'SELECT (SELECT GROUP_CONCAT(idLab) FROM _group_link b INNER JOIN _groups c ON c.id=b.id_group WHERE b.id=a.origId AND b.id_type = a.id_type GROUP BY b.id ) as unique_showAllGroups,a.* from '.
						"(SELECT id,id as origId,username,password,Firstname,Surname,0 as id_type FROM ".DB_WARPIT_WEBCATI_BASE.".`_Interviewer` UNION SELECT CONCAT('admin_',id) as id,id as origId,username,password,Firstname,Surname,1 as id_type FROM  ".DB_WARPIT_MAIN."._user) a"
				.' ';
			else
				$selectSQL = "SELECT (SELECT GROUP_CONCAT(idLab) FROM _group_link b INNER JOIN _groups c ON c.id=b.id_group WHERE b.id=a.id GROUP BY b.id ) as unique_showAllGroups,a.* FROM `_Interviewer` a";
		}
	}
	else if (  isset($_POST['template_id']) )
	{
		//template
		$showType = 2;
		$title = 'Query';
		$icon = 'icon_userspool_query';
		//the ajaxmanipulator fetches the rows from the query and builds the SQL statement 
		$baseParams = 'template_id:'.$_POST['template_id'];
		//let's add some special columns if the template requires (for example webPoints)
		$sql = "SELECT DISTINCT field_id FROM _QueryMachineConstruction WHERE id_template = ".$_POST['template_id']." AND field_id IN ('Total','Gained','Used')";
		$db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		$res = $db->SQLexecute($sql);
		while ($row = $db->fetchAssoc($res))
		{
			$fl = $row['field_id'];
			if($fl == 'Total')
				$specCol['totalPoints_tmp'] = $fl;
			else if($fl == 'Gained')
				$specCol['gained_tmp'] = $fl;
			else if($fl == 'Used')
				$specCol['used_tmp'] = $fl;
		}
		
	}

	$grid = new MakeGrid($tabId );
	$gridName = $grid->getName();
	//$grid->setGridName('skupina')
	
	
	$grid->setMainTable($tableName,$database)->setTitle("$title: ".$_POST['name']);
	$grid->selectSQL = $selectSQL;
	$grid->setReqUrl('webuserspool/_ajax/ajax.showgroup.php');
	$grid->baseParams = $baseParams;
	
		//$grid->addColumn('id');
	$grid->addColumn('id','ID user');

	if($showType == 1)
	{
		$grid->addColumn('unique_showAllGroups','Groups');
	}
	if($isWebcati)
	{
		
		$grid->addColumn('username','Username','new Ext.form.TextField()');
		$grid->addColumn('password','Password','new Ext.form.TextField()')->renderer("function(val,md,rec){
			return rec.id.substring(0,5) == 'admin'? '*****' : val;
	}");
		$grid->addColumn('Firstname','Firstname','new Ext.form.TextField()');
		$grid->addColumn('Surname','Surname','new Ext.form.TextField()');
	}
	else
	{
   		$addEditor = true;
		include ('grid.showgroup.php');
	}

	if($showType == 0)
	{
    	$grid->activateAdd('Add','icon-add-record',"var grTree = Ext.getCmp( '$grpTree');
									if( grTree ) grTree.updateNode( $groupId );");
    	$grid->addTbarItem ("{text:'Delete',iconCls:'icon-delete-record' , 
    		menu:[
    		{
				text:'Remove selected from group',
				iconCls:'icon-delete-record' , 
				handler: function(){
					var sel = $grid.getSelectedIds();
					if(sel.length > 0)
					Ext.Msg.show({ title:'Remove '+sel.length+ ' record'+( sel.length==1 ? '':'s') ,buttons: Ext.MessageBox.YESNO,msg:'Are you sure?',
					fn: function(btn){if(btn == 'yes'){
						$grid.RMconn.request({
							params:{ action:'delete',ids:sel.join() },
							success:function(res,opt){ $grid.getStore().reload();
									var grTree = Ext.getCmp( '$grpTree');
									if( grTree ) grTree.updateNode( $groupId );
							}
						});
					}
				}});}
    		}
    		,{ //removes all filtered users from this group
    			text: 'Remove all from group',
    			iconCls:'icon-delete-record' , 
	 			handler: function() { 
				Ext.Msg.show({ title:'Remove users',buttons: Ext.MessageBox.YESNO,
					msg: 'This will remove '+$gridName.getStore().getTotalCount() +' users from this group!</br>Are you sure?',
					fn: function(btn){if(btn == 'yes'){
						$grid.getStore().baseParams.addOn = 'removeUsers';
						$gridName.getStore().reload({
							callback:function(res,opt){ $grid.getStore().reload();
													var grTree = Ext.getCmp( '$grpTree');
													if( grTree ) grTree.updateNode( $groupId ); }
						}); 
					  }} })
			}} 
    		,
    		{//delete users from _Interviewer database!
				text:'Delete selected users',
				iconCls:'RMicon_delete_user3' , 
				handler: function(){
					var sel = $grid.getSelectedIds();
					if(sel.length > 0)
					Ext.Msg.show({ title:'Delete '+sel.length+ ' user'+( sel.length==1 ? '':'s') ,buttons: Ext.MessageBox.YESNO,msg:'Are you sure?',
					fn: function(btn){if(btn == 'yes'){
						$grid.RMconn.request({
							params:{ action:'deleteUsers',ids:sel.join() },
							callback:function(res,opt){ $grid.getStore().reload();var grTree = Ext.getCmp( '$grpTree');
									if( grTree ) grTree.updateNode( $groupId ); }
						});
					}
				}});}
    		}
    		,
    		{
    			text: 'Delete all users',
    			iconCls:'RMicon_delete_user3' , 
	 			handler: function() { 
				Ext.Msg.show({ title:'Delete users',buttons: Ext.MessageBox.YESNO,
					msg: 'This will delete '+$gridName.getStore().getTotalCount() +' users, that are in this group!</br>Are you sure?',
					fn: function(btn){if(btn == 'yes'){
						$grid.getStore().baseParams.addOn = 'deleteUsers';
						$gridName.getStore().reload({
							callback:function(res,opt){ $grid.getStore().reload();var grTree = Ext.getCmp( '$grpTree');
									if( grTree ) grTree.updateNode( $groupId ); }
						}); 
					  }} });
		}} 
		]
	} ");
	}
    else if( isset($_POST['group_id']))
		$grid->activateRemove('Delete');
		
		
	
		
	$grid->setPaging()
		//->setAutoExpand('email')
		->setCheckBoxSelectionModel(true)
		->setRemoteSort()
		->setFiltering(true)
		->addExportButton('Export',null,array('title' => "Export interviewers; Group: ".$_POST['name'] ))
		->setSearchField('Search','top',0,"['unique_showAllGroups','gained_tmp','totalPoints_tmp','used_tmp']")
		//we add a afteredit callback to check whether mail is duplicated!!!
		->setEditable(true,"function(resp,opt){
		var respDec = Ext.decode(resp.responseText);
		if(respDec.success){
				if(respDec.newValue)
					e.record.data[e.field] = respDec.newValue;
				 e.record.commit(); 
				  }
				  else {
					  //we check whether the email was duplicated!
					  if(respDec.error == 'mailDuplicate')
					  {
					  	var messege;
					  	if(respDec.groups.length > 0)
					  	{
					  		messege = 'This user already exists in groups<br>'+respDec.groups.join();
					  	}
					  	else
					  		messege = 'This user already exists, but is in no groups!';
					  	Ext.Msg.confirm('Error',messege+
					  	'<br>Do you want to remove this user<br> and copy '+e.value+' to this group?',
					  	function(btn){if(btn == 'yes'){
					  		$gridName.RMconn.request({ params:{action:'mailDuplicate',dupId:respDec.dupId,newId:e.record.data.id  },
					  		success: function(resp2){ $gridName.getStore().reload();  }  } );
					  	} });
						  
					  }
					  e.record.reject();
				  }
		}")
		->addConfig('enableDragDrop','true')
		->addConfig('ddGroup',"'wupGrouplink'")
		->addConfig('isWebcati',$isWebcati ? 'true' : 'false')
		->addConfig('iconCls',"'$icon'")
		->addConfig('copyMoveFunc',"function(onlySel,copyMode){
				//we add webuserspool tab, so that it shows/adds it!
				var grTree = Ext.getCmp( '$grpTree');
				if(!grTree) { addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'});Ext.Msg.alert('Warning!','Please select a group!'); return;}
				var n = grTree.getSelectionModel().getSelectedNode();
				if(n && n.isLeaf() ". ($isWebcati ? " && n.attributes.id.substring(0,9) == 'interview' && n.attributes.id.substring(10) != '$groupId'  ":" && n.id != '$groupId'")  . " ){
					//if a node is selected we copy/move all/selected data to the node
					var sel = $grid.getSelectedIds();
								
					var selNum = onlySel ? sel.length : $gridName.getStore().getTotalCount();
					var cmText = copyMode ? 'Copy' : 'Move';
					Ext.Msg.confirm(cmText + (onlySel ? \" selected\" : \" all\") + \" to '\"+n.attributes.idLab+\"'\",
					(copyMode ? '' : 'This will remove '+ selNum +' records from this group!<br>' ) + 'Are you sure?'
					,function(btn){
						if(btn == 'yes')
						{
							if( onlySel)
							{
								if(sel.length == 0) return;
								$grid.RMconn.request({
										params:{ action:'copyUser',ids:sel.join(),toGroup: ".($isWebcati ? "n.attributes.id.substring(10)" : "n.id")."
										, copyMode: copyMode },
										success:function(res,opt){ $grid.getStore().reload(); 
														if(!copyMode) grTree.updateNode( $groupId );
														grTree.updateNode( n.id );
										}
									});
							}
							else
							{
								$grid.getStore().baseParams.addOn = copyMode ? 'copy' : 'move';
								$grid.getStore().baseParams.toGroup = ".($isWebcati ? "n.attributes.id.substring(10)" : "n.id").";
								$gridName.getStore().reload({callback:function(r,opt,s){ 
								Ext.Msg.alert('Success',cmText+' succesful'); 
														grTree.updateNode( n.id );
									if(!copyMode)
									{//we refresh the grid and cancel the search (couse all have been removed :)
										var srcF = $grid.plugins[1];
										srcF.field.setValue('');
										srcF.onTriggerSearch();
										grTree.updateNode( $groupId );
									}
								 }
								});
							}
						
						}
					});
				}	
				else 
				{
					Ext.Msg.alert('Warning!','Please select a group!');
				}
	
		
		            	
	
	
	}");
		
		$copyMenu[] = "{text: 'Copy all',handler: function(){
				$grid.copyMoveFunc(false,true);
		} }";
		$copyMenu[] = "{text: 'Copy selected',handler: function(){
				$grid.copyMoveFunc(true,true);
		} }";
		if($showType == 0)	
		{
			$copyMenu[] = "{text: 'Move all',handler: function(){
				$grid.copyMoveFunc(false,false);
			} }";
			$copyMenu[] = "{text: 'Move selected',handler: function(){
					$grid.copyMoveFunc(true,false);
			} }";			
		}
		$grid->addtBarItem("{text:'Copy/move',dragCopy:true,iconCls:'RMicon_copy',menu:[
		". implode(',',$copyMenu) . "]}")
		
		;
	if($showType == 0)	
	{
	/*			$grid->addTbarItem("{text:'Move all',dragMove:true,iconCls:'RMicon_copy',
		handler:function(){
			//we add webuserspool tab, so that it shows/adds it!
		//	addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'},function(){
					var grTree = Ext.getCmp( '$grpTree');
					if(!grTree) return;
					//	grTree.show();
					var n = grTree.getSelectionModel().getSelectedNode();
					if(n && n.isLeaf() ". ($isWebcati ? " && n.attributes.id.substring(0,9) == 'interview' && n.attributes.id.substring(10) != '$groupId'  ":" && n.id != '$groupId'")  . " ){
						//if a node is selected we copy all data to the node
						Ext.Msg.confirm(\"Move all to '\"+n.text+\"'\",'This will remove '+$gridName.getStore().getTotalCount() +' records from this group!<br>Are you sure?',function(btn){
							if(btn == 'yes')
							{
								$grid.getStore().baseParams.addOn = 'move';
								$grid.getStore().baseParams.toGroup = ".($isWebcati ? "n.attributes.id.substring(10)" : "n.id").";
								$gridName.getStore().reload({callback:function(r,opt,s){
									Ext.Msg.alert('Success','Move succesful'); 
									
									}
								});
							
							}
						});
					}	
					else 
					{
						Ext.Msg.alert('Warning!','Please select a group!');
					}
		//	});//eo addTabAuto callback!
			
			            	
		
		
		}
			}");*/
			
		if(!$isWebcati)
		{	
	 		$grid->addTbarItem ("{ text:'Import',iconCls:'icon_import_database', 
	 		handler: function() { CallScript('webuserspool/_forms/window.fileUpload.php',{groupId:".$_POST['group_id'].",groupName:'".$_POST['name']."' }); }   }  ");
		
			$grid->addTbarItem ("{text:'Send mail',iconCls:'RMicon_send_email' , 
	 		handler: function() { CallScript('webuserspool/_forms/window.sendMailWizard.php',{groupId:".$_POST['group_id'].",groupGridName:'".$gridName."' }); }   }  ");
		}	
			
		
			
			
			
	}
 	
	$showDupsHandler = "var st = $grid.getStore();
 		st.lastOptions.params.showDups = s;
 		";
	if($showType == 0 )
		{ 
			$showDupsHandler .= "
			if(s)
				st.lastOptions.params.SQL = 'SELECT a.* from _group_link b INNER JOIN _Interviewer a INNER JOIN (SELECT COUNT(*) as cnt FROM _Interviewer  as d WHERE d.email != \'\' GROUP BY d.email HAVING cnt > 1 ) as c ON a.id = b.id';
			else
				st.lastOptions.params.SQL = 'SELECT a.* from _group_link b INNER JOIN _Interviewer a ON a.id = b.id';
			";
		}
		else if($showType == 1)
		{ 	//groups All!
			//$selectSQL = 'SELECT * from _Interviewer';
			$showDupsHandler .= "
				if(s)
					st.lastOptions.params.SQL =  'SELECT (SELECT GROUP_CONCAT(idLab) FROM _group_link e INNER JOIN _groups f ON f.id=e.id_group WHERE e.id=a.id GROUP BY e.id  ) as unique_showAllGroups,a.* FROM `_Interviewer` a INNER JOIN (SELECT COUNT(*) as cnt,b.email FROM _Interviewer  as b WHERE b.email != \'\' GROUP BY b.email HAVING cnt > 1 ) as c ON a.email = c.email';
				else
					st.lastOptions.params.SQL =  'SELECT (SELECT GROUP_CONCAT(idLab) FROM _group_link b INNER JOIN _groups c ON c.id=b.id_group WHERE b.id=a.id GROUP BY b.id  ) as unique_showAllGroups,a.* FROM `_Interviewer` a';
				";
		}
		$showDupsHandler .= "st.reload();";
	
 	/*$grid->addTbarItem("{text:'Show Duplicates',enableToggle:true ,toggleHandler:function(b,s){
 		$showDupsHandler
 		
 	}}");*/
 	
 	//echo $grid->createStore();
	echo $grid->createGrid();
	
	echo "
		$gridName.getStore().on('load',function(st){
			delete st.lastOptions.params.addOn;
			delete st.baseParams.addOn;
		});
		$gridName.on('afterrender',function(gr){ 
			
		/*	gr.RMdd = new Ext.dd.DragSource(gr.getTopToolbar().find('dragCopy',true)[0].getEl(),{ddGroup:'wupGrouplink',onStartDrag:function(){
				this.dragData = {caGrid : $gridName , isWebcati: ".($isWebcati ? 'true': 'false') ." };
			}} );*/
			
				$gridName.on('show',function(gr){ 
				gr.getStore().reload();
				});
		});
		$gridName.on('beforedestroy',function(gr){
			if(gr.RMdd) gr.RMdd.destroy();
		});
		
		
		$gridName.getColumnModel().on('columnmoved',function(col,oldInd,newInd){
			$gridName.RMconn.request({
				params:{action:'columnMove',newInd:newInd,oldInd:oldInd}
			});
		});
		$gridName.getColumnModel().on('hiddenchange',function(col,ind,hidden){
			$gridName.RMconn.request({
				params:{action:'columnHide',index:ind,hidden:hidden}
			});
		});
	
	mainTabPanel.add( Ext.getCmp( '".$grid->getGridName()."')).show();"; ?>