<?php

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

$tabId = $_POST['uniqueTabId'];
//convert tree id to project id!
$reqUrl = 'webcati/_ajax/webLinkStatistic/ajax.webLinkStatistic.php';


$projName = $_POST['name'];
$id_project = $_POST['id'];


$grpTree = 'PoolMenu_1';

$grid = new MakeGrid($tabId.'_usersPool');
$grid->setMainTable('_Interviewer',DB_WARPIT_USERSPOOL)
	//->activateRemove()
	->setCheckBoxSelectionModel()
	->setReqUrl($reqUrl)
	->setPaging()
	->setSearchField()
	->setFiltering()
/*	->addtBarItem("{text: 'Add fields',iconCls:'icon_userspool_fieldedit',handler:function(){
		CallScript('webuserspool/_forms/window.projectUserFields.php',{ projName:'$projName',compId:'$grid',id_project: $id_project });
	} }")*/
	->addtBarItem("{text:'Copy',dragCopy:true,iconCls:'RMicon_copy',
	menu: [{
		text: 'Copy selected',
		handler:function(){
			
		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()  ){
					//if a node is selected we copy/move all/selected data to the node
					var sel = $grid.getSelectedIds('id_user');
					if(sel.length == 0) return;
					var selNum = sel;
					var cmText = 'Copy';
					Ext.Msg.confirm(cmText + \" selected to '\"+n.text+\"'\",
					'Are you sure?'
					,function(btn){
						if(btn == 'yes')
						{
								
							new RMajax().request({
								url: 'webuserspool/_ajax/ajax.showgroup.php',
								params: {
									action:'copyUser',ids:sel.join(),toGroup: n.id
										, copyMode: true,database: '".DB_WARPIT_USERSPOOL."'
								},
								success: function()
								{
								    var tree = Ext.getCmp('". $grpTree ."');
								    tree.getLoader().load(tree.root);
								    tree.root.expand();
								}
							});
						}
					});
				}	
				else 
				{
					Ext.Msg.alert('Warning!','Please select a group!');
				}
	
		
		}
	},
	{
		text: 'Copy all',
		handler:function(){
			//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()  ){
					//if a node is selected we copy/move all/selected data to the node
								
					var selNum = $grid.getStore().getTotalCount();
					var cmText = 'Copy';
					Ext.Msg.confirm(cmText + \" all to '\"+n.text+\"'\",
					'Are you sure?'
					,function(btn){
						if(btn == 'yes')
						{
							
								$grid.getStore().baseParams.addOn = 'copy';
								$grid.getStore().baseParams.toGroup = n.id;
								$grid.getStore().reload({callback:function(r,opt,s){ 
								Ext.Msg.alert('Success',cmText+' succesful'); 
									
								 }
								});
						
						}
					});
				}	
				else 
				{
					Ext.Msg.alert('Warning!','Please select a group!');
				}
	}
	}]
	
		}")
/*	->addtBarItem("{text:'Reset interview',handler: function(){
		$grid.RMconn.request({params:{
			action: 'resetSurvey',
			ids: $grid.getSelectedIds(),
			id_project: $id_project
		}});
	}}")
	->addTbarItem ("{text:'Send mail',iconCls:'RMicon_send_email' , 
	 		handler: function() { CallScript('webuserspool/_forms/window.sendMailWizard.php',{sendProjUsers :true ,groupId:0,groupGridName:'".$grid."' }); }   }  ")*/
			
	->baseParams = "par: '{$_POST['id']}',type:2";;
//$grid->selectSQL =  "SELECT b.*,c.* FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids a INNER JOIN ".DB_WARPIT_USERSPOOL."._Interviewer b ON a.id_user = b.id LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".$projName"."_structure c ON a.id_user = c.user_id";

//$grid->addColumn('id_user','ID')->hidden(true)->table('a');
$grid->addColumn('id_loginSID','SID')->table('c');


//let's get all the fields that we need to show for zis user!
/*$sql = "SELECT a.*,b.field_name FROM _UserProjectFieldOrder a
	LEFT JOIN _InterviewerStructure b ON a.field_type = 2 AND b.id = a.id_field
	WHERE id_project = $id_project AND id_user = ".$_SESSION['UserInfo']['id']." ORDER BY orderBy";

echo "/*".$sql."";

$db->ChangeDatabase(DB_WARPIT_USERSPOOL);
$res = $db->SQLexecute($sql);
while ($row = $db->fetchAssoc($res))	
$rows[] = $row;*/
if(count($rows) == 0)
{
	//$rows[] = array('field_type' => 1,'id_field' => 1);
	$rows[] = array('field_type' => 1,'id_field' => 2);
	$rows[] = array('field_type' => 1,'id_field' => 3);
	$rows[] = array('field_type' => 1,'id_field' => 4);
	$rows[] = array('field_type' => 1,'id_field' => 5); 
	$rows[] = array('field_type' => 1,'id_field' => 6); 	
}
$grid->dateSQL = "U";
$grid->addColumn('flag_bad', "Flag bad")->hidden(true)->table('c');
foreach ($rows as $field)
	{
		switch ($field['field_type']) {
			case 1:
				switch ($field['id_field']) {
		//			case 1:	$grid->addColumn('email','Email')->width(150)->table('b'); break;
					case 2:	$grid->addColumn('status','Status')->type('int')->table('c')->renderer("function(v,obj,rec){
					       //ker statusi v sistemu očitno ne delujejo kot je treba uporabnika netegnemo da je drugačen status    
					       if(rec.get('flag_bad') == 99)
					           return 99;
                           return v;
                        }")->table('c');break;
					case 6:	$grid->addColumn('status_rec','Status Rec')->type('int')->table('c');break;
					case 3:	$grid->addColumn('t_start','Start')->type('date')->width(120)->renderer("function(v){
							if(v) return Ext.util.Format.date(v, 'd.m.Y h:i:s');
						}")->table('c');break;
					case 4:	$grid->addColumn('t_stop','End')->type('date')->width(120)->renderer("function(v){
					    if(v) return Ext.util.Format.date(v, 'd.m.Y h:i:s');
						}")->table('c');break;
					case 5:	$grid->addColumn('t_diffs','Duration')->type('string')->width(120)->renderer("function(v){
					   // Date.parseDate(val-3600,'U').format('H:i:s');
					     if(v)
						 return Date.parseDate(v-3600,'U').format('H:i:s');
						}")->table('c');break;
					}
			
			break;
			case 2:
				$grid->addColumn($field['field_name'],$field['field_name'])->type('string');	
			break; 
			case 3:
				$grid->addColumn($field['id_field'],$field['id_field'])->type('string');
			break;
		}
	}
	
$gridArray[] = $grid->getName();

$grid->addExportButton('Export','RMicon_export',array('ExportButtons' => array("CSV" => "CSV")));
echo $grid->createGrid();	

echo "$grid.getStore().on('load',function(st){
			delete st.lastOptions.params.addOn;
			delete st.baseParams.addOn;
		});";

echo "mainTabPanel.add({ 
		id:'$tabId',
		closable:true,
		title: 'Project - [".$id_project."] {$_POST['name']}',
		iconCls: 'icon-webuserspool-tab',
		layout:'fit',
		items:[
".implode(',',$gridArray). " ] }).show();";


?>