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

	
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);


$grid = new MakeGrid();
//$grid->setGridName('skupina')
$gridName = $grid->getName();

$duplicatedUsers = $_POST['duplicatedUsers'];
$newUsers = $_POST['newUsers'];
//grid for showing errors!
$gridError = new MakeGrid('ImportInterviewerErrorGrid');
	$errorGName = $gridError->getName();

	
	
	
$tabId = 'uGroupImportUsers';


$groupId = $_POST['groupId'];
$groupName = $_POST['groupName'];

$ImportTable = "data";

$grid->setMainTable($ImportTable,DB_WARPIT_USERSPOOL)->setTitle("Imported group");
$grid->selectSQL = "SELECT * FROM ".$ImportTable;


$grid->baseParams = "SQLwhere :'duplicated = 0'";


$grid->addColumn('id');
/*$grid->addColumn('firstname')->header('Firstname')->editor('new Ext.form.TextField()')->defaultValue('');
$grid->addColumn('email')->header('email')->editor('new Ext.form.TextField()')->defaultValue('');
$grid->addColumn('duplicated')->header('duplicated')->editor('new Ext.form.TextField()')->defaultValue('');	*/
$columns = json_decode(stripslashes($_POST['columns'])  );

foreach ($columns as $colName)
{
	$grid->addColumn($colName,$colName,'new Ext.form.TextField()');	
}

$grid->setEditable(true,"function(resp,opt){
	e.record.commit();
	if(e.grid.colModel.getColumnHeader(e.column) == 'email')
	{
		var r = Ext.decode(resp.responseText);
		var st = comboImported.getStore();
		st.getAt(0).data.displayText = 'Duplicated ( '+ r.duplicatedUsers + ' users)';
		st.getAt(1).data.displayText = 'Existing ( '+ r.existingUsers + ' users)';
		st.getAt(2).data.displayText = 'New ( '+ r.newUsers + ' users)';
		comboImported.bindStore(st);
		comboImported.setValue ( comboImported.getValue() );
		e.grid.getStore().reload();
	}
}")

?>

var comboImported = new Ext.form.ComboBox({
	width: 150,
    typeAhead: true,
    triggerAction: 'all',
    mode: 'local', 
    editable:false,
     
    store: new Ext.data.ArrayStore({
        fields: [
            'duplicated',
            'displayText'
        ],
        data: [ [2, 'Duplicated ( <?php echo $_POST['duplicatedUsers'];?> users)'], 
        		[1, 'Existing ( <?php echo $_POST['existingUsers'];?> users)'], 
        	   	[0, 'New ( <?php echo $_POST['newUsers'];?> users)']      	 	   
        	  ]
        	   	
    }),
   	 valueField: 'duplicated',
   	 displayField: 'displayText'
   	

	}); 

comboImported.setValue(0);	
	
comboImported.on('select', function(combo,rec) { 
	
	var s=<?php echo $grid->getGridName();?>.getStore();
	if(rec.data.duplicated == 2)
	{
		var dupSql = "SELECT a.* FROM <?php echo $ImportTable;?> as a INNER JOIN (SELECT COUNT(*) as cnt,b.email FROM <?php echo $ImportTable;?> as b WHERE b.email != '' GROUP BY b.email HAVING cnt > 1 ) as c ON a.email = c.email";
		delete s.lastOptions.params.SQLwhere;
		s.lastOptions.params['SQL'] = dupSql;
		s.lastOptions.params.sort = 'email';
		delete s.baseParams.SQLwhere;
		s.baseParams['SQL'] = dupSql;
		s.baseParams.sort = 'email';
		
	}
	else
	{
		delete s.lastOptions.params.SQL;
		s.lastOptions.params.SQLwhere = 'duplicated = ' + rec.data.duplicated;
		delete s.baseParams.SQL;
		s.baseParams.SQLwhere = 'duplicated = ' + rec.data.duplicated;
		
	}
	//console.log(s.baseParams);
	s.reload();
	

});
	
<?php



    $grid->activateRemove('Delete')
		->setPaging()
		->setRemoteSort()
		//->setAutoExpand('email')
		->setReqUrl('webuserspool/_ajax/ajax.showImportedGroup.php')
		->setCheckBoxSelectionModel(true)
		->setFiltering(true)
		->addtBarItem('comboImported')
	//	->setSearchField('Search')
		->addButton('Finish',"function(){
		var cols = [];
		var dis = [];
		var cm = $gridName.getColumnModel();
		for (var i=1;i<cm.getColumnCount();i++)
		{
			if(!cm.isHidden(i) )
			{
				cols.push(cm.getColumnHeader(i) );
				dis.push(cm.getDataIndex(i));
			}
		}
		var callBkcfun = function(resp,opt){
			
			var respT = Ext.decode(resp.responseText);
			if(true) //if the server response didn't fail
			{
				if(respT.success)
				{
					$tabId.ownerCt.remove($tabId);
					
					addTabAuto('wupShowGroup_'+$groupId,'webuserspool/_forms/forms.showgroup.php',{group_id: $groupId,name:'$groupName'});
				}
				else 
				{
					Ext.Msg.alert('Error',respT.error);
				}
				
			}
		}
		//first lets check if there are any duplicated records so that we can  bring up the window
		$errorGName.RMconn.request({params:{ action:'numDuplicated'},
			success:function(resp){
				var r = Ext.decode(resp.responseText);
				if(r.dupExist)
				{
					Ext.Msg.alert('Error','Duplicate users exist!')
				}
				else if(r.numDup > 0 )
				{
					//the tree for groups
					var wupImportGroupCombo = new Ext.ux.TreeCombo({autoHeight:true,loader : new Ext.tree.TreeLoader({
					 dataUrl   	:'_ajaxManipulators/treeDataManipulator.php', 
					 baseParams	: {RMtable:'_groups',database:'".DB_WARPIT_USERSPOOL."',action:'select',RMcomp:'tree', checked : 'leaf'} 
					,listeners: { load : function(a,b,resp){ var r = Ext.decode(resp.responseText); if(r!= null && r.success === false){ alert('Tree load error: '+r.error,'Error'); }  }
									} }
									) //eo treeLoader
					
									});	
				
					new Ext.Window({title:'Existing records!',modal:true,width:'280px',
						items:{
						xtype:'form', buttonAlign:'center',id:'wupImportForm',
						frame:true,
						items: [
						{xtype:'label',text:'What to do with existing records?'},
						{xtype:'radio',name:'importOpt', fieldLabel:'',boxLabel: 'Ignore',inputValue:0,checked:true},
						{xtype:'radio',name:'importOpt' ,boxLabel: 'Update',inputValue:1},
						{xtype:'label',text:'Copy existing to groups?'},
						wupImportGroupCombo
						]//eof form items
						 ,
						keys: [{
				               key: [Ext.EventObject.ENTER], fn: function(){
				                   Ext.getCmp('promptOKBtn').fireEvent('click');
				               }
				      		 }],
						buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
						click: function(){
						 			var form = Ext.getCmp('wupImportForm');
						 		
						 			
									$errorGName.RMconn.request({
									success: callBkcfun,
									params:{
									action:'importGroup',
									withDups: form.get(1).getGroupValue(),
									dupsToGroups: Ext.encode(	wupImportGroupCombo.treePanel.getChecked('id') ),
									groupId:".$_POST['groupId']."
									,origCols:Ext.encode(cols)
									,impCols:Ext.encode(dis)
									
								}});
								this.findParentByType('window').close();
										}
									}//eo listeners
								}//eo buttons
										  ,
						{
						text:'Cancel',handler:function(){ 
						this.findParentByType('window').close();
					
						 }
						 }
							  ] }
			   } ).show(); 
			   
			   
				}
				else 
				{ //if no duplicated records are in we import the new records
					$errorGName.RMconn.request({
						success:callBkcfun,
						params:{
						action:'importGroup',
						groupId:".$_POST['groupId']."
						,origCols:Ext.encode(cols)
						,impCols:Ext.encode(dis)
						
					}})
				}
				}});
			
		}")
		;
	
	// $grid->addTbarItem ("{ text:'Copy to group', handler: function() { CallScript('webuserspool/_forms/window.fileUpload.php',{}); }   }  ");
	
	//$grid->addTbarItem ("{ text:'Copy to group', handler: function() { alert(comboImported.getValue()); }   }");
	
	//a grid that shows all fields and an option to which field it should upload to
	
	$gridError->setMainTable('columnsData',DB_WARPIT_USERSPOOL)
				->setReqUrl('webuserspool/_ajax/ajax.showImportedGroup.php')
				->setEditable(false)
				->addtBarItem("{text:'Refresh',iconCls:'x-tbar-loading',handler:function(){
					SpecStoreorigCol{$gridError->rndID}.reload();
					{$gridError->getName()}.getStore().reload();
				}  }")
				->addButton('Next',"function(){
					var err = false;
					$errorGName.getStore().each(function(rec){
						if(rec.data.origCol == 0)
						{ //if some data is not set we show a warning
							Ext.Msg.alert('Warning!','Column for \''+rec.data.importCol+'\' not set!' );
							err = true;
							return false;
						}
						else 
						{ //else we find that columnt and rename the header (we will use headers as indexes then) or remove it if ignore is set!
							var colInd = $gridName.getColumnModel().findColumnIndex(rec.data.importCol);
							if(rec.data.origCol == '[Ignore]')
								$gridName.getColumnModel().setHidden(colInd,true);
							$gridName.getColumnModel().setColumnHeader(colInd,rec.data.origCol);	
						}
					});
					if(err) return;
					$tabId.getLayout().setActiveItem(1);". ($_POST['duplicatedUsers'] > 0 ? "Ext.Msg.alert('Warning!','Duplicated users found!');" : "" ) .
  			"}")
				;
	$gridError->addColumn('importCol','Imported Column');
	
	$gridError->addColumn('origCol','Upload column')->type('combo')
	->comboTable('_InterviewerStructure','remote')->comboDisplay('importCol')->comboValue('importCol');
	
	
	echo $grid->createGrid();
	echo $gridError->createGrid();
	
	echo "$errorGName.getStore().on('load',function(st,recs){
		if(recs.length == 0)
			$tabId.getLayout().setActiveItem(1);
	});
	var $tabId = new Ext.Panel({
		id:'$tabId',
		closable:true,
		iconCls:'icon_import_database',
		layout:'card',
		activeItem:0,
		title:'Import to: ".$_POST['groupName']."',
		items:[".$gridError->getGridName().",".$grid->getGridName()." ]
	});";
	
	echo "mainTabPanel.add( $tabId ).show();"; ?>