<?php
/**
 * Created by PhpStorm.
 * User: Jure
 * Date: 22.9.2014
 * Time: 13:40
 */
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;

}*/


//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!
 */


$gridStatistic = "UniqueStatisticInterviewersId" . $_POST['project_id'];

$tabIdVisitControl = "UniqueInterviewersVisitManager" . $_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($tabIdVisitControl);
$gridName = $grid->getName();
$projectId = $_POST['project_id'];

$sql = "SELECT c.id_nfield_project as id FROM _Projects as c WHERE c.id = '$projectId' ";
$result = $db->SQLexecute($sql);
if (!$result) {
    return "{success:false,error:'Error in get title of nfield projects'}";

}
$projectNfield = $db->fetchAssoc($result);
$projectNfieldId = $projectNfield['id'];

$storeGrades = 'storeControlDataGrades';
echo "var $storeGrades = new Ext.data.ArrayStore({
	        	        fields: ['id','grade'],
	        	        data: [[1, '1'], [2, '2'], [3, '3'],[4,'4'],[5,'5']]
	        	    });";



//Ime podatkovne baze moramo določiti v nastavitvah(config)
$grid->setMainTable($projectSamplePointTableName, 'nfield')->setTitle("Visit interviewers");
$grid->setReqUrl('capi_manager/_forms/control/_ajax/ajax.control_interviewers.php')->setHeight('700');
$grid->addColumn('id', '#')->width(40)->hidden(true);
$grid->addColumn('id_structure', 'Id structure')->width(80);
$grid->addColumn('check_status', 'Ocena', 'new Ext.form.TextField()')
    ->editor("new Ext.form.ComboBox({store:$storeGrades,
			valueField:'id',
			displayField:'grade',
			mode:'local',
			triggerAction:'all'
			})")
    ->width(60);
$grid->addColumn('comment', 'Pripomba', 'new Ext.form.TextField()')->width(120);
$grid->addColumn('check_status_date', 'Datum kontrole', 'new Ext.form.TextField()')->width(130);
$grid->addColumn('AnketarImePriimek', 'Anketar', 'new Ext.form.TextField()')->width(120);

//construction columns from nfield config
$db->ChangeDatabase('nfield');
$sql = "SELECT c.*  FROM nfield_config as c WHERE c.fk_id_nfield_project = '$projectNfieldId'";
$result = $db->SQLexecute($sql);
if (!$result) {
    return "{success:false,error:'Error with fetching nfield config'}";
}

while ($row = $db->fetchAssoc($result)) {

    if($row['label'] == 'Latitude' || $row['label'] == 'Longtitude'){
        $trimmedLabel = str_replace(' ', '', $row['label']);
        $grid->addColumn($trimmedLabel,$row['label'],'new Ext.form.TextField()')->width($row['width']);
    }
}
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
/*$grid->addColumn('Naslov', 'Naslov', 'new Ext.form.TextField()')->width(120);
$grid->addColumn('Anketar', 'Id Anketar', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('Telefon', 'Telefon', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('Komentar', 'Komentar', 'new Ext.form.TextField()')->width(120);
$grid->addColumn('AnketarImePriimek', 'Anketar', 'new Ext.form.TextField()')->width(120);
$grid->addColumn('Datum_ankete', 'Datum ankete', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('Start', 'Start', 'new Ext.form.TextField()')->width(40);
$grid->addColumn('Stop', 'Stop', 'new Ext.form.TextField()')->width(40);
$grid->addColumn('Spol', 'Spol', 'new Ext.form.TextField()')->width(30);
$grid->addColumn('Starost', 'Starost', 'new Ext.form.TextField()')->width(30);
$grid->addColumn('Zaposlitev', 'Zaposlitev', 'new Ext.form.TextField()');
$grid->addColumn('Stevilo_clanov_vecje_15', 'Število članov > 15', 'new Ext.form.TextField()');
$grid->addColumn('Stevilo_otrok_<_10_let', 'Stevilo otrok < 10 let', 'new Ext.form.TextField()');
$grid->addColumn('Stevilo_otrok_10_in_14', 'Stevilo otrok 10 - 14', 'new Ext.form.TextField()');
$grid->addColumn('Ime_in_Priimek', 'Ime in priimek', 'new Ext.form.TextField()')->width(90);*/


/*$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(400)
    ->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('viewConfig',"
    {
     stripeRows:false,
     getRowClass:function(record){

        var number = record.get('check_status');
        //return 'grade-row';
        return 'grade' + number;
     }
    }
    ")

    ->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("{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 . "' }); }   }  ");
*/


$classForComboBos = '"x-boundlist-item"';
$grid->addTbarItem("{text:'Show on map',iconCls:'icon-add-record',
    handler: function() {

      var tmp_rec_project_sample = $tabIdVisitControl.getSelectionModel();

				if(tmp_rec_project_sample.hasSelection() )
				{
                    var data = [];
                    Ext.each( tmp_rec_project_sample.getSelections() , function(rec){
                        if(rec.data.Latitude != '' || rec.data.Longtitude != ''){
                            object = {
                                id:rec.id,
                                latitude:rec.data.Latitude,
                                longitude:rec.data.Longtitude
                            }
                            data.push(object);


                        }
                        else{
                             Ext.MessageBox.show({
                                 title: 'Notice',
                                 msg: 'Gps coordinate not defined',
                                 buttons: Ext.MessageBox.OK,
                                 icon: Ext.MessageBox.ERROR
                            });
                        }

                        if(data[0] != null){
								CallScript('capi_manager/_forms/visit/window.map.php', { data: Ext.encode(data) });
						}

                        //data.push(rec.id);
                    } );




				}
				else{
				 Ext.MessageBox.show({
                        title: 'Notice',
                        msg: 'For showing you must select interviewer',
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
				}
     }

     } ");
/*$grid->addTbarItem("{
                    xtype:'combo',
                    id:'webCatiNfieldControlInterviewerCombo',
                    width: 140,
                    fieldLabel: 'Interviewers',
                    mode: 'local',
                    editable: true,
                    //tpl:new Ext.XTemplate('<tpl for="."><div class = $classForComboBos>{FirstName} {LastName}</div></tpl>'),
                    triggerAction:'all',
				    store:  new Ext.data.JsonStore({
                            url: 'nfield/Helpers/interviewersData.php',
                            root: 'rows',
                            autoLoad:true,
                            totalProperty: 'results',
                            fields:[{name: 'ClientInterviewerId'},{name: 'FirstNameLastName'}]
                        }),
				    valueField: 'ClientInterviewerId',
				    displayField: 'FirstNameLastName'
        }");
$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 }
                        });
            }
            }");



$grid->addtBarItem("{xtype:'button',id:'checkControlInterviewersBtn',iconCls:'icon-add-record',text:'Pregledano',
            handler: function(){

                       $gridName.getStore().reload({
                                     params:{ action:'select',filterTrigger:'1'}
                        });
            }
            }");



$grid->addtBarItem("{xtype:'button',id:'nonCheckControlInterviewersBtn',iconCls:'icon-add-record',text:'Odprto',
            handler: function(){

                       $gridName.getStore().reload({
                                     params:{ action:'select',filterTrigger:'2'}
                        });
            }
            }");
$grid->addtBarItem("{xtype:'button',id:'allControlInterviewersBtn',iconCls:'icon-add-record',text:'Vse',
            handler: function(){

                       $gridName.getStore().reload({
                                     params:{ action:'select',filterTrigger:'-1'}
                        });
            }
            }");
$grid->addtBarItem("{xtype:'button',id:'collapseInterviewersStatBtn',iconCls:'icon-add-record',text:'Show statistic',
            pressed: false,
            enableToggle:true,
            toggleHandler: function(button, pressed){
                    if(pressed){
                           Ext.getCmp('$gridStatistic').expand();

                     }
                    else {

                       Ext.getCmp('$gridStatistic').collapse();
                    }
            }}");

$grid->addtBarItem('"->"');
/*$grid->addtBarItem("{xtype:'button',id:'configManagerCtrlBtn',iconCls:'icon-add-record',text:'Config',
            handler: function(){

            CallScript('capi_manager/_forms/control/forms.config_control.php',{
				id_nfield_project:'$projectNfieldId'
			});


            }
            }");


$grid->addtBarItem("{xtype:'button',id:'downloadControlInterviewerOpenWindow',iconCls:'icon-add-record',text:'Download',
            handler:function(){

            new Ext.Window({title:'Before download control data',modal:true,width:'380px',height:'500px',
            items:{
            xtype:'form', buttonAlign:'center',
            frame:true,
            items: [

                {xtype:'checkbox',id:'controlInterviewersCheckBoxDeleteAll' , fieldLabel:'Delete all data',width: 200,allowBlank:false},
                {xtype:'checkbox',id:'controlInterviewersCheckBoxDeleteRaw' , fieldLabel:'Delete raw data',width: 200,allowBlank:false},

                {xtype:'datefield',id:'controlInterviewersStartDatetime' ,
                    format:'Y-m-d',
                    //value: new Date()-10,
                    fieldLabel:'Date from',
                    width: 200,
                    allowBlank:false,
                    listeners : {
                    render : function(datefield) {
                        var today = new Date();
                        var yesterday = new Date();
                        yesterday.setDate(today.getDate()-10);
                        datefield.setValue(yesterday);
                        }
                        }
                    },
                {xtype:'datefield',id:'controlInterviewersEndDatetime' ,format:'Y-m-d',value: new Date(),fieldLabel:'Date to',width: 200,allowBlank:false}

            ],
            keys: [{
                   key: [Ext.EventObject.ENTER], fn: function(){
                       Ext.getCmp('promptOKBtn').fireEvent('click');
                   }
                 }],
            buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
            click: function(){
                    if(Ext.getCmp('controlInterviewersStartDatetime').isValid() && Ext.getCmp('controlInterviewersEndDatetime').isValid() )
                    {
                	var deleteAllValue = Ext.getCmp('controlInterviewersCheckBoxDeleteAll').getValue();
                	var deleteRawValue = Ext.getCmp('controlInterviewersCheckBoxDeleteRaw').getValue();
                	var startDatetime = Ext.getCmp('controlInterviewersStartDatetime').getValue();
                	var endDatetime = Ext.getCmp('controlInterviewersEndDatetime').getValue();
                    //Download data process
                    Ext.MessageBox.show({
                   msg: 'Downloading control interviewers data, please wait...',
                   progressText: 'Saving...',
                   width:300,
                   wait:true,
                   waitConfig: {interval:200},
                   animateTarget: 'mb7',
                   icon: Ext.MessageBox.WARNING
               });
                 Ext.Ajax.timeout = 90000;
                 Ext.Ajax.request({url:'nfield/control/NfieldControlManager.php',params:{action:'saveControlDataOnServer',endDatetime:endDatetime,startDatetime:startDatetime, nfield_id:'$projectNfieldId'},
                    success: function(resp){
                    var r = Ext.decode(resp.responseText);
                        if(r.success){
                             $gridName.RMconn.request({
                                timeout:3000,
                                params:{ action:'parseControlInterviewersData',deleteAll:deleteAllValue,deleteRaw:deleteRawValue,
                                },
                                failure:function(){
                                     Ext.MessageBox.hide();
                                },
                                success:function(resp){

                                    Ext.MessageBox.hide();
                                     var savingResult = Ext.decode(resp.responseText);
                                    if(savingResult.success){
                                        //Here we insert datetime refresh for downloading
                                         Ext.MessageBox.show({
                                            title: 'Saving data was success',
                                            msg: savingResult.message,
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.INFO
                                         });
                                         $gridName.getStore().reload();
                                     }else{
                                         Ext.MessageBox.show({
                                            title: 'Saving data may not success',
                                            msg: savingResult.error,
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.ERROR
                                         });
                                     }
                                }
                             });
                        }else{
                            Ext.MessageBox.hide();
                            Ext.MessageBox.show({
                            title: 'Download was not success',
                            msg: r.error,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                        }
                    },
                    failure:function(){
                        Ext.MessageBox.hide();
                        Ext.MessageBox.show({
                            title: 'Saving was not success',
                            msg: 'Time request has expired. Please try again.',
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                    }
                    });
                    this.findParentByType('window').close();
		    }
	        }
	        }
			  },
		{
		text:'Cancel',handler:function(){
		    this.findParentByType('window').close();

		 }
		 }
			  ] },
	            defaultButton:'controlInterviewersCheckBoxDeleteAll'
			   } ).show();


            }

            }");*/

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