<?php
/**
 * Created by PhpStorm.
 * User: Jure
 * Date: 25.6.2014
 * Time: 17:16
 */


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


$tableName = '_Interviewer';

$project_id = $_POST['project_id'];
$tabIdInterviewersCapiCommon = "UniqueTabIdCapiManagerCommon" . $project_id;


$projectSamplePointTableName = $_POST['project_text'] . '___sample';
//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!
 */

$grid = new MakeGrid($tabIdInterviewersCapiCommon);
$gridName = $grid->getName();
$selectSQL = "SELECT i.* FROM _Interviewer i, _group_link w WHERE i.id = w.id";
$grid->setMainTable($tableName, DB_WARPIT_WEBCATI_BASE)->setTitle("Interviewers");
$grid->selectSQL = $selectSQL;
$grid->setReqUrl('capi_manager_common/_forms/interviewers/_ajax/ajax.interviewers.php');
$grid->addColumn('id', '#')->hidden(true);
$grid->addColumn('nfield_id', 'Id nfield', 'new Ext.form.TextField()')->width(250)->hidden(true);
$grid->addColumn('Firstname', 'Firstname', 'new Ext.form.TextField()')->width(90);
$grid->addColumn('Surname', 'Surname', 'new Ext.form.TextField()')->width(90);
$grid->addColumn('SIPPhoneID', 'SIP Phone ID', 'new Ext.form.TextField()')->hidden(true);
$grid->addColumn('SIPPass', 'SIP Password', 'new Ext.form.TextField()')->hidden(true);
$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;}")->width(90);


//Here we set parameters for the request
$grid->baseParams = "project_id:'" . $project_id . "',projectSampleTableName:'$projectSamplePointTableName'";

/*$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 ); }
						});
					  }} });
		}}
		]
	} "
);

*/


$grid->setPaging()
    ->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();  }  } );
					  	} });

					  }
					  else
					  if(respDec.error == 'editAdminNotAllowed')
					  {
					  	Ext.Msg.show({
					  		title:'Forbidden',
					  		msg:'You are not allowed to change the data of other Administrator!',
					  		buttons: Ext.Msg.OK,
					  		icon: Ext.MessageBox.ERROR
					  	});
					  }else
					  if(respDec.error == 'sipuserexists')
					  {
					  	Ext.Msg.show({
					  		title:'SIP username in use',
					  		msg:'The SIP username -' + respDec.sip + '- is in use by ' + respDec.user + '!',
					  		buttons: Ext.Msg.OK,
					  		icon: Ext.MessageBox.ERROR
					  	});
					  }

					  e.record.reject();
				  }
		}")

    ->addConfig('enableDragDrop', 'true')
    ->addConfig('ddGroup', "'wupGrouplink'")
    ->addConfig('iconCls', "'$icon'");
$grid->addtBarItem("{xtype:'button',id:'insertInterviewerNfield',iconCls:'icon-add-record',text:'Add',
            handler: function(){
                    $gridName.RMconn.request({
							    params:{ action:'insert'

							    },
							    success:function(){
				                     $gridName.getStore().reload();
			                    },

							    callback:function(res,opt){

							    }
						    });

            }
            }");
//$grid->addtBarItem('"->"');

$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) . "]}");*/


/*$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 . "' }); }   }  ");
*/
echo $grid->createGrid();

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

            $grid.on('show',function(gr){
                gr.getStore().reload();

                });
		});
		$grid.on('beforedestroy',function(gr){
			if(gr.RMdd) gr.RMdd.destroy();
		});


		$grid.getColumnModel().on('columnmoved',function(col,oldInd,newInd){
			$grid.RMconn.request({
				params:{action:'columnMove',newInd:newInd,oldInd:oldInd}
			});
		});
		$grid.getColumnModel().on('hiddenchange',function(col,ind,hidden){
			$grid.RMconn.request({
				params:{action:'columnHide',index:ind,hidden:hidden}
			});
		});

	"; ?>