<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Jure
 * Date: 21.3.14
 * Time: 12:53
 * 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");


$tableName = '_Interviewer';

$project_id = $_POST['project_id'];
$tabIdInterviewers = "UniqueTabIdCapiManager" . $project_id;

$projectSamplePointTableName = $_POST['project_text'] . '___sample';

$grid = new MakeGrid($tabIdInterviewers);
$gridName = $grid->getName();

$selectSQL = "SELECT i.* FROM _Interviewer i, _www_ids w, ".$projectSamplePointTableName." as p WHERE i.id = w.id_user AND p.user_id = i.id AND w.id_project = ".$project_id."";

$grid->setMainTable($tableName, DB_WARPIT_WEBCATI_BASE)->setTitle("Interviewers");
$grid->selectSQL = $selectSQL;

//$grid->setReqUrl('webuserspool/_ajax/ajax.showgroup.php');
$grid->setReqUrl('capi_manager/_forms/interviewers/_ajax/ajax.interviewers.php');
//$grid->baseParams = ' gridType: \'usersPool\'';
$grid->addColumn('id', '#')->hidden(true);
$grid->addColumn('Firstname', 'Firstname', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('Surname', 'Surname', 'new Ext.form.TextField()')->width(80);
$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(80);

//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->addtBarItem("{xtype:'button',id:'toogleButtonInterviewer',iconCls:'icon-add-record',text:'Show all',
            pressed: false,
            enableToggle:true,
            toggleHandler: function(button, pressed){

                    if(pressed){
                           $gridName.getStore().reload({
                                         params:{ action:'getAll'}
                            });
                             button.setText('Show assigned');
                            }
                    else {
                        button.setText('Show all');
                        $gridName.getStore().reload({
                                         params:{ action:'getAssignOnProject'}});
                        }
            }
            }");


$grid->setPaging()
    ->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('"->"');
$grid->addtBarItem("{xtype:'button',id:'buttonDownloadInterviewers',iconCls:'icon-add-record',text:'Download',
            handler: function(){
                 Ext.MessageBox.show({
                   msg: 'Downloading interviewers, please wait...',
                   progressText: 'Saving...',
                   width:300,
                   wait:true,
                   waitConfig: {interval:200},
                   animateTarget: 'mb7',
                   icon: Ext.MessageBox.WARNING
               });

                 Ext.Ajax.request({url:'nfield/interviewers/NfieldInterviewersManager.php',
                 params:{action:'saveDownloadedInterviewers',
                         projectSampleTableName:'$projectSamplePointTableName'
                         },
                    success: function(resp){
                    var r = Ext.decode(resp.responseText);
                        if(r.success){
                           Ext.MessageBox.hide();
                            Ext.MessageBox.show({
                            title: 'Download interviewers success',
                            msg: r.message,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        }else{
                            Ext.MessageBox.hide();
                            Ext.MessageBox.show({
                            title: 'Download was not success',
                            msg: r.error,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                        }
                    }
                    });
            }
            }");
$grid->addtBarItem("{xtype:'button',id:'buttonUploadInterviewers',iconCls:'icon-add-record',text:'Upload',
            handler: function(){
                 Ext.MessageBox.show({
                   msg: 'Uploading interviewers, please wait...',
                   progressText: 'Saving...',
                   width:300,
                   wait:true,
                   waitConfig: {interval:200},
                   animateTarget: 'mb7',
                   icon: Ext.MessageBox.WARNING
               });

                 Ext.Ajax.request({url:'nfield/interviewers/NfieldInterviewersManager.php',
                 params:{action:'uploadInterviewers',
                         projectSampleTableName:'$projectSamplePointTableName'
                         },
                    success: function(resp){
                    var r = Ext.decode(resp.responseText);
                        if(r.success){
                           Ext.MessageBox.hide();
                            Ext.MessageBox.show({
                            title: 'Upload interviewers success',
                            msg: r.message,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        }else{
                            Ext.MessageBox.hide();
                            Ext.MessageBox.show({
                            title: 'Upload was not success',
                            msg: r.error,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                        }
                    }
                    });
            }
            }");

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

	"; ?>