<?php
/**
 * Created by PhpStorm.
 * User: Jure
 * Date: 18.6.2014
 * Time: 15:28
 */

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


$tabIdConfigControl= "UniqueConfigControlManager".$_POST['project_id'];

$projectText = $_POST['project_text'];
$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);
$id_nfield_project = $projectNfield['id'];


$grid = new MakeGrid($tabIdConfigControl);
$gridName = $grid->getName();
$grid->setMainTable('nfield_config','nfield')->setTitle("Config");
$grid->setReqUrl('capi_manager/_forms/control/_ajax/ajax.config_control.php')->setWidth('700');


$grid->addColumn('id', '#', 'new Ext.form.TextField()')->width(40)->hidden(true);
$grid->addColumn('code', 'Koda', 'new Ext.form.TextField()')->width(80);
$grid->addColumn('label', 'Naziv', 'new Ext.form.TextField()')->width(90);
$grid->addColumn('coordinate', 'Koordinate', 'new Ext.form.TextField()')->width(60);
$grid->addColumn('width', 'Širina', 'new Ext.form.TextField()')->width(35);
$grid->addColumn('update_date', 'Datum', 'new Ext.form.TextField()')->width(130);
$grid->addColumn('fk_id_nfield_project', 'TK', 'new Ext.form.TextField()')->width(80)->hidden(true);

//Here we set parameters for the request
$grid->baseParams =  "id_nfield_project:'" . $id_nfield_project . "'";

$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:'button',id:'configControlAddBtn',iconCls:'icon-add-record',text:'New',
            handler: function(){

            $gridName.RMconn.request({
							    params:{ action:'insert'

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

							    callback:function(res,opt){

							    }
						    });
            }
            }");

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

				if(tmp_rec_config.hasSelection() )
				{
                    Ext.Msg.show({ title:'Question',icon: Ext.MessageBox.INFO,buttons: Ext.MessageBox.YESNO,msg:'Are you want remove selected property?',
                    fn: function(btn){if(btn == 'yes'){

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

                            } );

                            $gridName.RMconn.request({
							    params:{ action:'delete',
                                         id:selectedProjectSampleId.join()


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

							    callback:function(res,opt){

							    }
						    });
                        }
                        }});
				}
				else{
				 Ext.MessageBox.show({
                        title: 'Notice',
                        msg: 'First you must select property',
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
				}
     } } ");

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

            var nfieldProjectsStore =  new Ext.data.JsonStore({
            url: 'nfield/Helpers/nfieldProjectsData.php',
            root: 'rows',
            autoLoad:true,
            totalProperty: 'results',
            fields:[{name: 'id_nfield_project'},{name: 'name_nfield_project'}]
            });

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

                {
                    xtype:'combo',
                    id:'controlNfieldProjectCombo',
                    width: 140,
                    fieldLabel: 'Nfield project',
                    mode: 'local',
                    editable: true,
                    triggerAction:'all',
                    store: nfieldProjectsStore,
                    valueField: 'id_nfield_project',
                    displayField: 'name_nfield_project'
                }
            ]//eof form items
             ,
            keys: [{
                   key: [Ext.EventObject.ENTER], fn: function(){
                       Ext.getCmp('controlSubmitCopyOKBtn').fireEvent('click');
                   }
                 }],
            buttons:[{text:'Ok',id:'controlSubmitCopyOKBtn',listeners:{
            click: function(){

                    var comboNfieldProject = Ext.getCmp('controlNfieldProjectCombo');
                    var selectedNfieldProject = comboNfieldProject.getValue();
                    var selectedNfieldProjectName = comboNfieldProject.getRawValue();

                    $gridName.RMconn.request({
							    params:{ action:'copy',
                                         selectNfieldId:selectedNfieldProject
							    },
							    success:function(){



				                     $gridName.getStore().reload();
			                    },

							    callback:function(res,opt){

							    }
						    });
                     this.findParentByType('window').close();
		    }
	}
			  },
		{
		text:'Cancel',handler:function(){
		    this.findParentByType('window').close();

		 }
		 }
			  ] },
	            defaultButton:'controlNfieldProjectCombo'
			   } ).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}
                });
		});
	";?>


