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


$grid = new MakeGrid();
$tabId = $_POST['uniqueTabId'];
$projectId = $_POST['id_project'];
$projName = $_POST['projName'];
$tableName = $projName.'___telIndex';
$database = DB_WARPIT_WEBCATI_BASE;

//let's check if there is any telIndex table
if(!$db->TableExists($projName.'___telIndex',DB_WARPIT_WEBCATI_BASE))
{
	echo "Ext.Msg.alert('Error','There is no telephone sample reserved for the project!');
	removeSession('$tabId')";
	exit;
}

// if I have custom telephone fields, I need ID of telephone table
$id_telname = $db->get('_Projects',$projectId,'id_telname',DB_WARPIT_WEBCATI_BASE);
$telTable = 'tel___'.$db->get('_TelephoneTables',$id_telname,'name',DB_WARPIT_WEBCATI_BASE);

$grid = new MakeGrid();

$countGrid = new MakeGrid();

$grid->setMainTable($tableName,DB_WARPIT_WEBCATI_BASE);

// I need additional columns, if exists
$extraFields = $db->get('_TelephoneTablesAddon','id_telbaza = '.$id_telname.' AND is_leaf = 1','name' );
if(is_array($extraFields)) {
	$sql_extraFields = ",b.tel_".implode(",b.tel_", $extraFields);
	// put all possible sort fields to ajax request
	$str_extraFields = "oms,tel_".implode(",tel_", $extraFields);
}


$grid->selectSQL = "SELECT a.*,a.id, a.status,b.oms,b.telephone,b.name $sql_extraFields FROM $tableName a INNER JOIN $telTable b ON a.id_tel = b.id";
$grid->setReqUrl('webcati/_ajax/telNumberManagment/ajax.appointmentMan.php');
//$grid->baseParams = "SQLwhere : '(a.status = 91 OR a.status = 89)'";
$grid->baseParams = "SQLwhere : '(a.status IN (21,22,24,25,89,91) AND a.tdisable=0)', str_extraFields : '$str_extraFields'";

$grid->addColumn('id');
$grid->addColumn('statIcon');
$grid->addColumn('statTooltip');
$grid->addRowAction('icons',"new Ext.ux.grid.RowActions({
	
	actions:[{
		iconIndex:'statIcon',
		qtipIndex:'statTooltip'
		},
		{
		iconCls:'RMicon_delete_app',
		tooltip:'Delete'
		},
		{
		iconCls:'RMicon_reactivate_app',
		tooltip:'Reactivate'
		}
	],
	listeners: {
		action: function(g,r,a){
			var act;
			if(a == 'RMicon_cancel_app') act = 'cancelApp';
			else if(a == 'RMicon_restore_app') act = 'restoreApp';
			else if(a == 'RMicon_delete_app') act = 'deleteApp';
			else if(a == 'RMicon_reactivate_app') act = 'reactivateApp';
			$grid.RMconn.request({params:{
				action:act,
				id:r.id},
				success:function(){ $grid.getStore().reload(); $countGrid.getStore().reload();}
			});
		}
	}
})");
$grid->addSetter("'app_time','id_ank'");
	
$grid->addColumn('id','ID')->type('int')->width(40)->tableAs('a');
$grid->addColumn('tdisable','tdisable')->type('checkColumn')->width(60)->tableAs('a');
$grid->addColumn('status','Status')->type('int')->width(50)->tableAs('a');
$grid->addColumn('status_rec','Status rec')->type('int')->width(50)->tableAs('a');
$grid->addColumn('call_num','No. of calls')->type('int')->width(50);
$grid->addColumn('id_tel','Id tel.')->type('int')->width(50);
$grid->addColumn('id_ank','Int. ID')->type('int')->width(50)->editor("new Ext.form.NumberField()");
//oms and telefon from the tel___database!
//$grid->addColumn('oms','Tel. num.')->type('int')->width(150)->renderer("function(val,md,rec){return val+'/'+rec.data.telephone;}");
$grid->addColumn('oms','Area code')->width(50)->tableAs('b');
$grid->addColumn('telephone','Telephone')->width(150)->tableAs('b');
$grid->addColumn('name','Name')->width(200);
$grid->addColumn('region','Region')->type('int')->tableAs('b');
//$grid->addColumn('ime','Name');

//adding all custom fields to the grid
	//$extraFields = $db->get('_TelephoneTablesAddon','id_telbaza = '.$id_telname.' AND is_leaf = 1','name' );
	if(is_array($extraFields)) {
		foreach ($extraFields as $telField) {
			$grid->addColumn('tel_'.$telField,$telField)->tableAs('b');
		}
	}


$grid->dateSQL = 'U';
$grid->dateDisplay = 'd.m.Y H:i:s';

$grid->addColumn('last_call','Last call')->type('date')->width(200);
//$grid->addColumn('call_time',"Call time")->type('date')->width(200)->editor('new Ext.ux.form.DateTime()');

$grid->addColumn('app_time','Next call time (app, busy, no answer)')->type('date')->width(200)->editor('new Ext.ux.form.DateTime()');
$grid->addColumn('app_call_this_num','New call number')->width(150)->editor('new Ext.form.TextField()');
$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->setAutoExpand('id_tel');
$grid->setCheckBoxSelectionModel()
	->setSearchField()
	->setFiltering()
	->region('center');

$grid->setPaging()
	->region('center')
	->setCheckBoxSelectionModel(true)
	->setRemoteSort()
	->setFiltering(true)
	->setSearchField('Search','top');

$grid->addtBarItem("{
			text:'On hold',
			iconCls:'cancelMultiAppointments',
			handler:function(bt,state){

			var q = $grid.selModel.getSelections();
			if(q) {
				var qId = new Array();
				for(var i=0;i<q.length;i++)
					qId.push( q[i].id );
			}
			$grid.RMconn.request({
					  url:'webcati/_ajax/telNumberManagment/ajax.appointmentActions.php',
					  params:{action:'MultiCancel', database:'$database', RMtable:'$tableName', selRecords:Ext.encode(qId) },
					  success:function(){ 
					  	$grid.getStore().reload();
					  }
				})
       		}
	   }");
				 
$grid->addtBarItem("{
			text:'Restore',
			iconCls:'restoreMultiAppointments',
			handler:function(bt,state){

			var q = $grid.selModel.getSelections();
			if(q) {
				var qId = new Array();
				for(var i=0;i<q.length;i++)
					qId.push( q[i].id );
			}
			$grid.RMconn.request({
					  url:'webcati/_ajax/telNumberManagment/ajax.appointmentActions.php',
					  params:{action:'MultiRestore', database:'$database', RMtable:'$tableName', selRecords:Ext.encode(qId) },
					  success:function(){ 
					  	$grid.getStore().reload();
					  }
				})
       		}
	   }");
	   
$grid->addtBarItem("{
			text:'Delete',
			iconCls:'deleteMultiAppointments',
			handler:function(bt,state){

			var q = $grid.selModel.getSelections();
			if(q) {
				var qId = new Array();
				for(var i=0;i<q.length;i++)
					qId.push( q[i].id );
			}
			$grid.RMconn.request({
					  url:'webcati/_ajax/telNumberManagment/ajax.appointmentActions.php',
					  params:{action:'MultiDelete', database:'$database', RMtable:'$tableName', selRecords:Ext.encode(qId) },
					  success:function(){ 
					  	$grid.getStore().reload();
					  }
				})
       		}
	   }");

$grid->addtBarItem("{
			text:'Reactivate',
			iconCls:'reactivateMultiAppointments',
			handler:function(bt,state){

			var q = $grid.selModel.getSelections();
			if(q) {
				var qId = new Array();
				for(var i=0;i<q.length;i++)
					qId.push( q[i].id );
			}
			$grid.RMconn.request({
					  url:'webcati/_ajax/telNumberManagment/ajax.appointmentActions.php',
					  params:{action:'MultiReactivate', database:'$database', RMtable:'$tableName', selRecords:Ext.encode(qId) },
					  success:function(){ 
					  	$grid.getStore().reload();
					  }
				})
       		}
	   }");


/*
$grid->addTbarItem(" new Ext.form.ComboBox({
	    typeAhead: true,
	    triggerAction: 'all',
	    mode: 'local',  
	    store: new Ext.data.ArrayStore({
	        fields: [
	            'filID',
	            'displayText'
	        ],
	        data: [	
	        		[1,' Show all numbers'],
	        	 	[2,' Show only available numbers (tdisable = 0)']
	        	  ]
	   	 }),
	   	 valueField: 'filID',
	   	 value: '1',
	   	 displayField: 'displayText',
	   	  listeners: {
	   	 	select : function(combo,rec) {
				$grid.getStore().reload({params:{ ShowFilter : rec.get('filID')} });
	   	 	}
	   	 }
	   	 
		}) ");
*/


$grid->addListener('beforerender',"function(){
	this.getStore().on('beforeload',function(){
		$countGrid.getStore().reload();
	});
}");
	   
	   
	
$countGrid->setTitle('Appointments count');
$countGrid->setMainTable($tableName,DB_WARPIT_WEBCATI_BASE);
$countGrid->setReqUrl('webcati/_ajax/telNumberManagment/ajax.appointmentMan.php');
$countGrid->baseParams = "countGrid : true";
$countGrid->setAutoLoad(false);
$countGrid->addColumn('date','Date');
//$countGrid->addColumn('count','All numbers');
$countGrid->addColumn('count','Available numbers');
//$countGrid->addColumn('countAvail','Available numbers');
$countGrid->setHeight(200)->region('south');

echo $grid->createGrid();
echo $countGrid->createGrid();

echo "$grid.getStore().on('update',function(a,b,c){ if(c=='commit') $countGrid.getStore().reload(); });
mainTabPanel.add({
		id:'$tabId',
		title:'Calls scheduler - $projName',
		iconCls:'RMicon_Appointment',
		closable:true,
		layout:'border',
		items: [$grid,$countGrid]
}).show();";

?>