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

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

	// if I come from menu directly, I have ID of project not proj!
	if (!$_POST['id_proj']) $_POST['id_proj'] = $_POST['id_project'];
	
	$tableName = $db->get('_Projects',$_POST['id_proj'],'proj_name',DB_WARPIT_WEBCATI_BASE).'___telIndex';
	
	// if I come from menu directly, I do not have ID of telephone table
	if (!$_POST['id_telTable']) $_POST['id_telTable'] = $db->get('_Projects',$_POST['id_proj'],'id_telname',DB_WARPIT_WEBCATI_BASE);
	
	$telephoneTable = $db->get('_TelephoneTables ',$_POST['id_telTable'],'name',DB_WARPIT_WEBCATI_BASE);
//echo $telephoneTable;
	
	// I need also index table...
	//let's check if there is any telIndex table
	if(!$db->TableExists($tableName,DB_WARPIT_WEBCATI_BASE))
	{
		echo "alert('No telephone database exist for project $tableName')
		removeSession('$tabId')";
		exit;
	}

/*
	//I need type of the add fields to set the find renderer
	$sql1 = "SELECT name,type FROM _TelephoneTablesAddon WHERE id_telbaza=".$_POST['id_telTable']." AND is_leaf=1";
	if (!$res1 = $db->SQLexecute( $sql1 )) {
		echo "alert('Error requesting custom telephone field(s)!')
		removeSession('$tabId')";
		exit;
	}
	while($row1 = $db->fetchAssoc($res1)){
		if ($row1['type'] == 4 OR $row1['type'] == 5) 
			$addFieldType = "int";
		else if ($row1['type'] == 7)
			$addFieldType = "checkColumn";
		else if ($row1['type'] == 8)
			$addFieldType = "date";
		else
			unset($addTelType[$row1['name']]);
			
		$addTelType[$row1['name']] = $addFieldType;
	}
*/
					
					
	$tabId = $_POST['uniqueTabId'];
	//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( 'grid_'.$tabId );
	
	// I need additional columns, if exists
	$extraFields = $db->get('_TelephoneTablesAddon','id_telbaza = '.$_POST['id_telTable'].' AND is_leaf = 1','name' );
	if(is_array($extraFields)) {
		$sql_extraFields = ",b.tel_".implode(",b.tel_", $extraFields);
		$str_extraFields = "oms,tel_".implode(",tel_", $extraFields);
	}
	$grid->setMainTable($tableName,DB_WARPIT_WEBCATI_BASE)->setTitle('Numbers')
	->setReqUrl("webcati/_ajax/telNumberManagment/ajax.manageTelTable.php")
	->dateSQL = 'U';
	
	$grid->addSetter("'tdisable','region','status','status_rec','call_time','call_num'");
	
	$grid->dateDisplay = 'd.m.Y H:i:s';
	$grid->addColumn('id','Id')->width(50)->tableAs('a');
	$grid->addColumn('id_tel','Id Tel.')->width(50)->type('int');
	$grid->addColumn('tdisable','Dis')->type('checkColumn')->width(30)->tableAs('a');
	$grid->addColumn('oms','oms',"new Ext.form.NumberField()")->tableAs('a')->width(30);
	$grid->addColumn('telephone','Telephone',"new Ext.form.TextField()")->tableAs('b')->width(60);
	$grid->addColumn('region','Region',"new Ext.form.TextField()")->type('int')->tableAs('a')->width(50);
	$grid->addColumn('town','Town');
	$grid->addColumn('zip','ZIP',"new Ext.form.TextField()")->width(50)->tableAs('a');
	$grid->addColumn('name','Name')->width(200);
	$grid->addColumn('address','Adress')->width(200);
	$grid->addColumn('id_import',"Import seq.")->type('int')->width(80);
	$grid->addColumn('status',"Status","new Ext.form.NumberField()")->type('int')->tableAs('a');
	$grid->addColumn('status_rec',"Status rec","new Ext.form.NumberField()")->type('int')->tableAs('a');
	$grid->addColumn('last_call',"Last Call")->type('date')->width(200)->renderer("function(v) {
                 if(v.format('U') > 100) return Ext.util.Format.date(v, 'd.m.Y H:i:s');
            }");
	$grid->addColumn('call_num',"Num. of calls")->type('int')->width(80);
	$grid->addColumn('callback',"Callback")->type('int')->width(60);
	$grid->addColumn('call_time',"Call 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');
            }")->editor('new Ext.ux.form.DateTime()');
	
	//$extraFields = $db->get('_TelephoneTablesAddon','id_telbaza = '.$_POST['id_telTable'].' AND is_leaf = 1','name' );
	if(is_array($extraFields))
	{
		foreach ($extraFields as $telField) {
			$grid->addColumn('tel_'.$telField,$telField)->editor('new Ext.form.TextField()')->tableAs('b');
		}
		
	}
	$grid->addColumn('status_comment','Status comment')->width(200)->editor('new Ext.form.TextField()');
	$grid->addColumn('app_koment','Appointment comment')->width(200)->editor('new Ext.form.TextField()');

	$grid->addExportButton('Export','RMicon_export',array(),true);
	
	$grid->setPaging()
		//->setAutoExpand('email')
		->region('center')
		->setCheckBoxSelectionModel(true)
		->setRemoteSort()
		->setFiltering(true)
		->setSearchField('Search','top')
		->addTbarItem("'&nbsp;&nbsp;&nbsp;&nbsp;',{
			text:'Set Appointment',
			iconCls:'RMicon_Appointment',
			handler: function(){
			
				var selIds = $grid.getSelectedIds();
				if(selIds.length == 0) return;
				var w = new Ext.Window({
					autoDestroy:false,
					title:'Set appointments',
					items:[new Ext.ux.form.DateTime({
						ref:'valueToSet',fieldLabel : 'Appointment time'
					}) ]
					,layout:'form'
					,height:120,
					width:400
					,labelWidth:130,
					labelAlign:'right',
					padding:'15',
					modal:true
					,
					buttons:[{text:'Ok',
						handler: function(){
						var val = w.valueToSet.getValue();
						val = Ext.util.Format.date(val, 'U');
						
						
							$grid.RMconn.request({
								params:{
									action:'setAppointments',
									ids: selIds.join(),
									setValue:val
								},
								success: function(){
									$grid.store.reload();
								}
							});
						
							w.close();
					} },{
						text:'Cancel',handler:function(){
						w.close();
					}
					}]
			
			}).show();
			}
			
		}")
		->baseParams = "id_telTable:".$_POST['id_telTable'].",extraFields : '".$sql_extraFields ."', str_extraFields : '$str_extraFields'"
		;

$importSeq = array();
$importSeq[] = "[0,' All imports']";
$sql = "SELECT count(*) as n, id_import FROM tel___".$telephoneTable." GROUP BY id_import";
$resImport = $db->SQLexecute($sql);
while ($zadImport = $db->fetchAssoc($resImport)) $importSeq[] = "[".$zadImport['id_import'].", '".$zadImport['id_import']." - ( ".$zadImport['n']." numbers )']";

$grid->addTbarItem("'&nbsp;&nbsp;','-','&nbsp;&nbsp;','Import sequence filter:',new Ext.form.ComboBox({
	    typeAhead: true,
	    triggerAction: 'all',
	    mode: 'local', 
	    
	    store: new Ext.data.ArrayStore({
	        fields: [
	            'filID',
	            'displayText'
	        ],
	        data: [	
	        		".implode(",",$importSeq)."
	        	  ]
	    }),
	   	 valueField: 'filID',
	   	 value: '0',
	   	 displayField: 'displayText',
	   	 listeners: {
	   	 	select : function(combo,rec) {
	   	 		$grid.getStore().baseParams.ComboImportFilter = rec.get('filID');
	   	 		$grid.getStore().reload();
	   	 	}
	   	 }
		}) ");


unset($importSeq);


$telFilter = array();
$telFilter[] = "{id:0,displayText:' ------- Filters -------'}";
$telFilter[] = "{id:-1,displayText:' <b>Filter Administrator</b>'}";

$sql = "SELECT * FROM _TelephoneSampleFilters 
			WHERE 
					id_user = ".$_SESSION['UserInfo']['id']." 
				AND user_type = ".$_SESSION['UserInfo']['user_type']." 
				AND id_tel = ".$_POST['id_telTable']." 
			ORDER BY filterName ";

$sql = "SELECT * FROM _TelephoneSampleFilters 
			
			ORDER BY filterName ";
$resImport = $db->SQLexecute($sql);
while ($zadImport = $db->fetchAssoc($resImport)) $telFilter[] = "{id:".$zadImport['id'].", displayText: '".$zadImport['filterName']."',def:".$zadImport['filterDefinition']." }";

$grid->addTbarItem("'->','Grid filter: ',new Ext.form.ComboBox({
	    typeAhead: true,
	    triggerAction: 'all',
	    mode: 'local', 
	    
	    store: new Ext.data.JsonStore({
	        fields: [
	            'id',
	            'displayText',
	            'def',
	            'sort'
	        ],
	        url:'webcati/_ajax/telNumberManagment/ajax.manageTelTable.php',
	        baseParams:{
	        	action:'getFilters',
	        	id_telTable:".$_POST['id_telTable']." 
	        },
	        root:'rows'
	    }),
	     ref:'filterCombo',
	   	 valueField: 'id',
	   	// value: '0',
	   	 displayField: 'displayText',
	   	 listeners: {
	   	 	select : function(combo,rec) {
	   	 		combo.selectedId = rec.id;
	   	 		//$grid.getStore().reload({params:{ ComboFilterTemplate: rec.get('filID')  } } );
	   	 		//first we deactivate all other filters
	   	 		
	   	 		
	   	 		Ext.each($grid.gridFilter.filters.items,function(f)
	   	 		{
	   	 			//f.setActive(false);
	   	 			f.active=false;
	   	 		});
	   	 		//sometimes the store won't reload automaticly!
	   	 		var manualReload = true;
	   	 		if(rec.id == 0)
	   	 		{
	   	 			
	   	 			$grid.getStore().setDefaultSort('id','ASC');
	   	 			$grid.getStore().reload();
	   	 			return;
	   	 		}
	   	 		if(rec.data.sort)
	   	 		{

	   	 		
	   	 			var sd = rec.data.sort.split(',');
	   	 			$grid.getStore().setDefaultSort(sd[0],sd[1]);
	   	 		}
	   	 		for (var p in rec.data.def)
	   	 		{
	   	 			
	   	 		
	   	 			var f = $grid.gridFilter.getFilter(p);
	   	 			if(f.type != 'boolean') //if only booleans are set it won't reload...fucking scumbag extjs
	   	 			{
	   	 				manualReload = false;
	   	 			}	
	   	 			if(f.type == 'date')
	   	 			{	
	   	 				for(var key in rec.data.def[p])
	   	 				{
	   	 					rec.data.def[p][key] = Date.parseDate(rec.data.def[p][key],'Y-m-dTH:i:s');
	   	 				}
	   	 			}
	   	 			
	   	 			f.setValue(rec.data.def[p]);
	   	 			//f.inputItem.setValue(rec.data.def[p]);
	   	 			//f.setActive(true);
	   	 			f.active=true;
	   	 		}
	   	 		//lets sort it!
	   	 		if(manualReload)
	   	 			$grid.getStore().reload();
	   	 	
	   	 		return;
	   	 		
	   	 	},
	   	 	render:function()
	   	 	{
	   	 		this.getStore().load();
	   	 	} 
	   	 } 
		}),{text:'Save', 
			iconCls: 'icon_save_document',
			handler:function(){
			var f = $grid.gridFilter;
			var p = {};
			//debugger;
			f.filters.each(function (ff) {
				if(ff.active)
				{
					p['filter['+ff.dataIndex+']' ] =Ext.encode(ff.getValue());
				}
				}); 
			var ss = $grid.getStore().getSortState();
			if(ss)
				p.sortState =  ss.field + ',' + ss.direction;
			var name = $grid.getTopToolbar().filterCombo.getValue();
			if(name == -1 || name == 0)
			{
				Ext.Msg.alert('Error','Please select a filter or type a new name');
				return;
			}
			p.filterName = name;
			p.action= 'saveFilterState';
			$grid.RMconn.request({
				params:p	
				,success:function(resp){
					var rsp = Ext.decode(resp.responseText);
					
					var krp = $grid.getTopToolbar().filterCombo;
					krp.selectedId = rsp.insertId;
					krp.getStore().reload({callback:function(){
						krp.selectByValue( krp.getStore().find('displayText',krp.getValue())  );
					}});
				}
			})	;
		
		} },{
			text:'Delete',
			iconCls: 'icon-delete-record',
			handler: function(){
				var f = $grid.getTopToolbar().filterCombo;
				if(!f.selectedId) return;
				$grid.RMconn.request({
					params:{
						id: f.selectedId,
						action:'deleteFilter'
					},
					success:function(){
						f.getStore().reload();
						f.setValue(' ------- Reset -------');
						f.selectedId = 0;
						//ker pac v totem kurcastem EXTjs nic ne dela tak ko treba, moram to se enkrat tocno naret
						//jebes to sranje od EXTjs
						Ext.each($grid.gridFilter.filters.items,function(f)
			   	 		{
			   	 			//f.setActive(false);
			   	 			f.active=false;
			   	 		});
			   	 		$grid.getStore().setDefaultSort('id','ASC');
	   	 				$grid.getStore().reload();
					}
				});
			}
		},{
			text:'Rename',
			iconCls: 'RMicon_edit_record',
			handler:function(){
				var f = $grid.getTopToolbar().filterCombo;
				if(!f.selectedId) return;
				$grid.RMconn.request({
					params:{
						id: f.selectedId,
						action:'renameFilter',
						name: f.getValue()
					},
					success:function(){
						f.getStore().reload();
					}
				});
			}
		} ");
unset($telFilter);





echo $grid->createGrid();
	
	//echo $projGrid->createGrid();
/*	grid.getFilterPlugin().getFilter('dataindex').setValue("value"); //string filter
grid.getFilterPlugin().getFilter('dataindex').setValue(true); //bool filter
grid.getFilterPlugin().getFilter('dataindex').setValue({gt:2, lt:9, eq:5}); //numeric filter
grid.getFilterPlugin().getFilter('dataindex').setValue({before: new Date(2008,0,1), after:..., on:...}); //date filter
grid.getFilterPlugin().getFilter('dataindex').setValue(['item1', item2]); //list filter
*/

	echo "
	
	//filters".$grid->rndID.".getFilter('telephone').setValue('234'); 
	//filters".$grid->rndID.".getFilter('town').setValue('maribor'); 
	//filters".$grid->rndID.".getFilter('zip').setValue('1024'); 
	
	//filters".$grid->rndID.".getFilter('telephone').setActive(true);
	//filters".$grid->rndID.".getFilter('town').setActive(true);
	//filters".$grid->rndID.".getFilter('zip').setActive(true);*/
	
	mainTabPanel.add({
	id: '$tabId', 
	layout:'border',
	title: 'Preview sample - $tableName',
	iconCls:'RMicon_preview_cati',
	closable: true,
	items:[$grid]

	 })";
	 if(!$_POST['uniqueNotShow'])
		echo  ".show();";
?>