<?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;

}*/

$tabIdSamplePoint = "UniqueCapiManagerCommonSamplePointsManager" . $_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($tabIdSamplePoint);
$gridName = $grid->getName();
$grid->setMainTable($projectSamplePointTableName, DB_WARPIT_WEBCATI_BASE)->setTitle("Project sample points");
$grid->setReqUrl('capi_manager_common/_forms/assign_sample_point/_ajax/ajax.samplepoints.php')
->dateSQL = 'U';
	
$grid->dateDisplay = 'd.m.Y H:i:s';
$grid->addColumn('id', '#')->width(30);
$grid->addColumn('id_sample', 'Id sample', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('id_sampleTable', 'Sample table', 'new Ext.form.TextField()')->width(80);
//id_user
$grid->addColumn('user_id', 'Id user', 'new Ext.form.TextField()');
$grid->addColumn('username', 'Username'); 
$grid->addColumn('Firstname', 'Name', 'new Ext.form.TextField()');
$grid->addColumn('Surname', 'Surname', 'new Ext.form.TextField()');
$grid->addColumn('num_interviews', 'Target interviews', 'new Ext.form.TextField()');
$grid->addColumn('planned_visit_time', 'Planned time', 'new Ext.form.TextField()');

$grid->addColumn('id_municipality', 'Id municipality', 'new Ext.form.TextField()');
$grid->addColumn('municipality', 'Municipality', 'new Ext.form.TextField()');
$grid->addColumn('id_settlement', 'Id settlement', 'new Ext.form.TextField()');
$grid->addColumn('id_municipality', 'Id municipality', 'new Ext.form.TextField()');
$grid->addColumn('settlement', 'Settlement', 'new Ext.form.TextField()');
$grid->addColumn('id_street', 'Id street', 'new Ext.form.TextField()');
$grid->addColumn('street', 'Street', 'new Ext.form.TextField()');
$grid->addColumn('address', 'Address', 'new Ext.form.TextField()');
$grid->addColumn('addon_address', 'Addon address', 'new Ext.form.TextField()');
$grid->addColumn('zip', 'Zip', 'new Ext.form.TextField()');
$grid->addColumn('town', 'Town', 'new Ext.form.TextField()');
$grid->addColumn('name', 'Name', 'new Ext.form.TextField()');

$grid->addColumn('x_coordinate', 'X coordinate', 'new Ext.form.TextField()')->width(240);
$grid->addColumn('y_coordinate', 'Y coordinate', 'new Ext.form.TextField()');
$grid->addColumn('id_region', 'Id region', 'new Ext.form.TextField()')->width(140);
$grid->addColumn('population', 'Population', 'new Ext.form.TextField()')->width(50);
$grid->addColumn('type_settlement', 'Type settlement', 'new Ext.form.TextField()')->width(50);
$grid->addColumn('id_import', 'Id import', 'new Ext.form.TextField()')->width(50);
$grid->addColumn('time_import','Import time')->type('date')->width(200);/*->renderer("function(v) {
                 if(v.format('U') > 100) return Ext.util.Format.date(v, 'd.m.Y H:i:s');
            }");*/
//let's get extra fields
$project_id = $_POST['project_id'];

	$project_data = $db->get('_Projects','id = '.$project_id,'id_capiTable' );
	$extraFields = $db->get('_CapiTablesAddon','id_capiTable = '.$project_data[0].' AND is_leaf = 1 ORDER BY orderBy ASC','name' );
	if(is_array($extraFields)) {
		foreach ($extraFields as $telField) {
			$grid->addColumn('capi_'.$telField,$telField);
		}
	}
	



/*$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'];
//$baseParamsPager = 'start:'.'0';
$grid->baseParams =$baseParams.",projectSamplePointTableName:'" . $projectSamplePointTableName . "', selectType: 0";
/*$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("{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 . "' }); }   }  ");
*/
$grid->addTbarItem("{text:'Assign',iconCls:'icon-add-record',
    handler: function() {

    var tmp_rec_project_sample = $tabIdSamplePoint.getSelectionModel();
    
    var tmp_rec_interviewer = Ext.getCmp('UniqueTabIdCapiCommonAssignInterviers" . $_POST['project_id'] . "').getSelectionModel();
	//alert( '".$_POST['project_id']."');
    
				if(tmp_rec_interviewer.hasSelection() && tmp_rec_project_sample.hasSelection() )
				{
                    Ext.Msg.show({ title:'Question',icon: Ext.MessageBox.INFO,buttons: Ext.MessageBox.YESNO,msg:'Assign interviewer on sample point. Are you sure?',
                    fn: function(btn){if(btn == 'yes'){
                            var selectedIntervierId = [];
                            Ext.each( tmp_rec_interviewer.getSelections() , function(rec){
                                selectedIntervierId.push(rec.id);

                            } );

                            var selectedProjectSampleId = [];
                            Ext.each( tmp_rec_project_sample.getSelections() , function(rec){
                                selectedProjectSampleId.push(rec.id);

                            } );

                            $gridName.RMconn.request({
							    params:{ action:'assignInterviewer',
							             interviewer_id:selectedIntervierId.join(),
                                         project_sample_point_id:selectedProjectSampleId.join()


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

							    callback:function(res,opt){
                                    console.log('callback function()');
							    }
						    });
                        }
                        }});
				}
				else{
                     Ext.MessageBox.show({
                        title: 'Notice',
                        msg: 'For assign you must select interviewer and project sample points',
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
				}





     } } ");

$grid->addTbarItem("{text:'Unassign',iconCls:'icon-delete-record',
    handler: function() {
    var tmp_rec_project_sample = $tabIdSamplePoint.getSelectionModel();

				if(tmp_rec_project_sample.hasSelection() )
				{
                    Ext.Msg.show({ title:'Question',icon: Ext.MessageBox.INFO,buttons: Ext.MessageBox.YESNO,msg:'Are you want unassign interviewer from sample point?',
                    fn: function(btn){if(btn == 'yes'){

                            var selectedProjectSampleId = [];
                            Ext.each( tmp_rec_project_sample.getSelections() , function(rec){
                                selectedProjectSampleId.push(rec.id);

                            } );

                            $gridName.RMconn.request({
							    params:{ action:'unassignInterviewer',
                                         project_sample_point_id:selectedProjectSampleId.join()


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

							    callback:function(res,opt){
                                    console.log('callback function()');
							    }
						    });
                        }
                        }});
				}
				else{
				 Ext.MessageBox.show({
                        title: 'Notice',
                        msg: 'For unassign you must select project sample point/s',
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
				}
     } } ");
$grid->addtBarItem("{xtype:'button',id:'toogleButton',iconCls:'icon-add-record',text:'Show selected',
            pressed: false,
            enableToggle:true,
            toggleHandler: function(button, pressed){
                var tmp_rec_interviewer = Ext.getCmp('UniqueTabIdCapiCommonAssignInterviers" . $_POST['project_id'] . "').getSelectionModel();
                if(tmp_rec_interviewer.hasSelection() )
                {
                    if(pressed){
                             var selectedInterviewerId = [];
                            Ext.each( tmp_rec_interviewer.getSelections() , function(rec){
                                selectedInterviewerId.push(rec.id);

                            } );
							$gridName.getStore().baseParams.selectType = 2;
							$gridName.getStore().baseParams.user_id = selectedInterviewerId;
							$gridName.getStore().baseParams.start = $gridName.getStore().lastOptions.params.start;
							$gridName.getStore().baseParams.limit = $gridName.getStore().lastOptions.params.limit;
            				$gridName.getStore().load({
            					params: {
            					selectType : 2,
            					user_id: selectedInterviewerId
            					}
            				});
							if(Ext.getCmp('toogleNonAssignButton').pressed)
							{
								Ext.getCmp('toogleNonAssignButton').toggle(false, true);
								Ext.getCmp('toogleNonAssignButton').setText('Show unassigned');
							}
                            button.setText('Show all');
                            }
                    else {
                        button.setText('Show selected');
						$gridName.getStore().baseParams.selectType = 0;
						$gridName.getStore().baseParams.start = $gridName.getStore().lastOptions.params.start;
						$gridName.getStore().baseParams.limit = $gridName.getStore().lastOptions.params.limit;
        				$gridName.getStore().reload({
        					params: {
        						selectType : 0
        					}
        				});
                     }
				}
                else{
                 Ext.MessageBox.show({
                        title: 'Notice',
                        msg: 'If you want get assign sample points you must select interviewer',
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
					button.toggle(false, true);
                 }


            }
            }");

$grid->addtBarItem("{xtype:'button',id:'toogleNonAssignButton',iconCls:'icon-add-record',text:'Show unassigned',
            pressed: false,
            enableToggle:true,
            toggleHandler: function(button, pressed){
            	var selectType = 0;	
            	if(pressed) 
            	{
            		selectType = 1;
					button.setText('Show all');
					if(Ext.getCmp('toogleButton').pressed)
					{
						Ext.getCmp('toogleButton').toggle(false, true);
						Ext.getCmp('toogleButton').setText('Show selected');
					}
				}
				else					
					button.setText('Show unassigned');
				
				$gridName.getStore().baseParams.selectType = selectType;
				$gridName.getStore().baseParams.start = $gridName.getStore().lastOptions.params.start;
				$gridName.getStore().baseParams.limit = $gridName.getStore().lastOptions.params.limit;
            	$gridName.getStore().reload({
            		params: {
            			selectType : selectType
            		}
            	});	
				//console.log($gridName.getStore().lastOptions);
            	return;
				
                    if(pressed){
                           $gridName.getStore().reload({
                                         params:{ action:'getUnAssignedSamplePoints'
                                        }
                            });
                             button.setText('Show all');
                            }
                    else {
                        button.setText('Show unassigned');
                        $gridName.getStore().reload({
                                         params:{ action:'select'}});
                        }
            }
            }");

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