<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Jure
 * Date: 21.3.14
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 */
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT . "init.php");
include_once(PATH_TO_ROOT . "_class/class.Extjs_grid.php");


$projectSamplePointTableName = $_POST['project_text'] . '___sample';
/*if(!$db->TableExists($projectSamplePointTableName,DB_WARPIT_WEBCATI_BASE))
{
    echo "alert('No defined CAPI sample points for this project:$projectSamplePointTableName')";
    exit;

}*/

$tabIdInterviewerStatistic = "UniqueInterviewersStatisticManager" . $_POST['project_id'];
//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($tabIdInterviewerStatistic);
$gridName = $grid->getName();


//Code for combo boxes
/*echo "var $storeDataType = new Ext.data.ArrayStore({
        fields: [
            'myId',
            'displayText'
        ],
        data: [".implode(',',$comboStr).  "]
	});";
$fieldGrid->addColumn('type','Variable type')
    ->editor("new Ext.form.ComboBox({store:$storeDataType,
		valueField:'myId',
	displayField:'displayText',
	mode:'local',
	triggerAction:'all'
	})")
    ->renderer("function(val){
		var idx =$storeDataType.find('myId', val);
		if(idx==-1)	return 'Select';
		var rec = $storeDataType.getAt(idx);
		return rec.get('displayText');
	}"  );*/


//Ime podatkovne baze moramo določiti v nastavitvah(config)

$grid->setMainTable($projectSamplePointTableName, 'nfield')->setTitle("Statistic interviewers");
$grid->setReqUrl('capi_manager/_forms/control/_ajax/ajax.statistic_interviewers.php')->setHeight('700');
$grid->addColumn('AnketarImePriimek', 'Anketar', 'new Ext.form.TextField()')->width(120);
//$grid->addColumn('interviewer', 'Anketar')->width(70);
$grid->addColumn('control', 'Kontroliranih')->width(80);
$grid->addColumn('allSurvey', 'Vseh', 'new Ext.form.TextField()')->width(40);
$grid->addColumn('procent', '%', 'new Ext.form.TextField()')->width(55)->renderer("function(item) {
                 return item+' %';
            }");


/*$grid->activateAdd('Add', 'icon-add-record', "var grTree = Ext.getCmp( '$grpTree');
									if( grTree ) grTree.updateNode( $groupId );");*/
//Here we set parameters for the request

$baseParams = 'project_id:'. $_POST['project_id'];
$baseParamsProjectText = 'project_text:'. $_POST['project_text'];
//Listeners for edit
/*$grid->listeners[] = "afteredit:function(e){
	$labelGrid.RMconn.request({
		params: Ext.apply({action:'update',RMcomp:'labelGrid'},e.record.data),
		success:function(){e.record.commit()}
	});
}";*/


$grid->baseParams =  $baseParams.",project_text:'" . $_POST['project_text'] . "'";
/*$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'");
$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("{
                    xtype:'combo',
                    id:'webCatiNfieldControlInterviewerCombo',
                    width: 140,
                    fieldLabel: 'Interviewers',
                    mode: 'local',
                    editable: false,
                    triggerAction:'all',
				    store:  new Ext.data.JsonStore({
                            url: 'nfield/Helpers/interviewersData.php',
                            root: 'rows',
                            autoLoad:true,
                            totalProperty: 'results',
                            fields:[{name: 'ClientInterviewerId'},{name: 'FirstName'}]
                        }),
				    valueField: 'ClientInterviewerId',
				    displayField: 'FirstName'
        }");
$grid->addtBarItem("{xtype:'button',id:'interviewerFilterControlBtn',iconCls:'icon-add-record',text:'Prikaži',
            handler: function(){
                       var comboNfieldInterviewers = Ext.getCmp('webCatiNfieldControlInterviewerCombo');
		               var selectedNfieldInterviewers = comboNfieldInterviewers.getValue();

                       $gridName.getStore().reload({
                                     params:{ action:'select',filterTrigger:'3',interviewerId:selectedNfieldInterviewers }
                        });
            }
            }");*/
echo $grid->createGrid();

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

            $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}
                });
		});
	";?>