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


$callsGrid = new MakeGrid();
$tabId = $_POST['uniqueTabId'];
$projectId = $_POST['id_project'];
$projName = $_POST['projName'];
$tableName = $projName;

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

//let's get the name of the telephone database table and the layer that is used to select telephone numberzzz
/*$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
$sql = "SELECT name,id_select_layer FROM _Projects a INNER JOIN _TelephoneTables b ON id_telname  = b.id WHERE a.id = $projectId";
*/
//$db->LogWrite($sql,false,"izberem layer in q_name");


/*if(!$res = $db->SQLexecute($sql)){ echo $db->JsonError(); exit;}
$row = $db->fetchArray($res);
$telTable = 'tel___'.$row[0];
*/

$callsGrid = new MakeGrid();

$callsGrid->setMainTable($tableName,DB_WARPIT_WEBCATI_BASE);
//$callsGrid->selectSQL = "SELECT a.*,b.oms,b.telefon,b.ime FROM $tableName a INNER JOIN $telTable b ON a.id_tel = b.id";
$callsGrid->setReqUrl('webcati/_ajax/telNumberManagment/ajax.callStatistics.php')
	->setTitle('Calls statistics')
	//->setPaging(400)
	;

$callsGrid->addColumn('id');

$callsGrid->addColumn('agent','<b>Agent</b>');
	
	/*$sql = "SELECT q_name, layer, id_question, source FROM quota_layer WHERE id_project = ".$projectId."  ORDER BY layer,zap_st ";
	//echo $sql;
	
	$res =  $db->SQLexecute($sql);
	$i = 1;
	
	while ($row = $db->fetchRow($res))
	{
		// row[3] is controling the type of variable.... in grid are added only telephone variables
		if (!$questionControl[$row[0]] && $row[3] < 2) {
			$statHidden = "true";
			
			$callsGrid->addColumn($row[0],'<b>'.$row[0].'</b>')->setProperty('isVar','true')->setProperty('hidden',$statHidden)->setProperty('id','\'col_'.$row[0].'\'');//->renderer("function(val,met,rec){return val+' '+rec.data.".$row[0]."_label; } ");
			$telephoneVarPosition[$row[0]] = $i;
			$i++;
		
		} elseif ($row[3] > 1) {
			// here I am saving all layers which include non telephone variables
			$deleteLayer[$row[1]] = $row[1];	
		}
		$questionControl[$row[0]] = $row[0];		
		$LayerList[$row[1]][] = $row[0];
	}
	
	
// delete all layers included not telephone variable
if ($deleteLayer) foreach ($deleteLayer as $val) unset($LayerList[$val]);	
	*/
	
$callsGrid->addColumn('calls','<b>Calls</b>');
//oms and telefon from the tel___database!
$callsGrid->addColumn('ok','<b>OK</b>')->setProperty('css',"'color:green;'");
$callsGrid->addColumn('failed','<b>Fail</b>')->setProperty('css',"'color:red;'");
$callsGrid->addColumn('busy','<b>Busy</b>');
$callsGrid->addColumn('noAnswer','<b>NoAns</b>');
$callsGrid->addColumn('noOp','<b>No Op</b>');
$callsGrid->addColumn('contact','<b>Contact</b>');
$callsGrid->addColumn('app','<b>App</b>');
$callsGrid->addColumn('forApp','<b>ForApp</b>');
$callsGrid->addColumn('charg','<b>Charg</b>');
$callsGrid->addColumn('reject','<b>Rejects</b>');
$callsGrid->addColumn('ignore','<b>Ignores</b>');
$callsGrid->addColumn('queued','<b>Queued Time</b>');
$callsGrid->addColumn('waitTime','<b>Wait time</b>');
$callsGrid->addColumn('convTime','<b>Conversation<br/>time</b>');
$callsGrid->addColumn('dataTime','<b>Data time</b>');
$callsGrid->addColumn('busyTime','<b>Busy time</b>');
$callsGrid->addColumn('pauseTime','<b>Pause time</b>');
$callsGrid->addColumn('total','<b>Total time</b>');

/*$callsGrid->addColumn('SUMavail','<b>SUM all<br> available</b>')->width('55')->setProperty('css',"'color:green;'");
$callsGrid->addColumn('TODO','<b>QUOTA<br>todo</b>')->width('55')->renderer("function(val) {			
		if (val > 0) return '<font color=green>' + val + '</font>';
		else if (val < 0) return '<font color=red>' + val + '</font>';
		return val;	
	}"  );


*/
$callsGrid->setSortable(false)
->region('center')
->addTbarItem("{iconCls:'x-tbar-loading',handler:function(){ $callsGrid.getStore().reload(); }}")
->flex(3);


/*if ($LayerList) {
	
	
	foreach ($telephoneVarPosition as $val) $extraHideColumnSyntax[] = $callsGrid.".getColumnModel().setHidden(".$val.",true); ";
	
	
	// prepare items for combo box. Here are all defined quota layers
	$_i = 1;
	foreach ($LayerList as $idLay=>$lay) {
		if (!$idLayer) {
			$sql = "UPDATE _Projects SET id_select_layer = '".$idLay."' WHERE id = ".$projectId;
			$db->SQLexecute($sql);
			$idLayer = $idLay;
			foreach ($lay as $val) $defaultColumnVisible[] =  $callsGrid.".getColumnModel().setHidden(".$telephoneVarPosition[$val].",false); ";
		}
		$tmpLay[] = "[".$idLay.", '".implode(" - ",$lay)."']"; 
		$tmp = "if (aLayer == ".$idLay.") { ";
			foreach ($lay as $val) $tmp .= $callsGrid.".getColumnModel().setHidden(".$telephoneVarPosition[$val].",false); ";
		$tmp .= " } ";
		$extraHideColumnSyntax[] = $tmp;
		
		$_i++;
	}



	$callsGrid->addTbarItem("new Ext.form.ComboBox({
	    typeAhead: true,
	    triggerAction: 'all',
	    mode: 'local',  
	    store: new Ext.data.ArrayStore({
	        fields: [
	            'layID',
	            'displayText'
	        ],
	        data: [	".implode(",",$tmpLay)."
	        	 	
	        	  ]
	    }),
	   	 valueField: 'layID',
	   	 value: '".$idLayer."',
	   	 displayField: 'displayText',
	   	 hideColumns : function(aLayer) {
	   	 	".implode(" ",$extraHideColumnSyntax)."
	   	 },
	   	 listeners: {
	   	 	select : function(combo,rec) {
	   	 		this.hideColumns(rec.get('layID'));
	   	 		$callsGrid.ComboLayer = rec.get('layID');
	   	 		$callsGrid.getStore().reload({params:{ hiddenVars:$callsGrid.hiddenVars.join(), ComboLayer: rec.get('layID') , ComboNumberFilter: $callsGrid.ComboNumberFilter, ComboImportFilter: $callsGrid.ComboImportFilter } } );
	   	 	}
	   	 }
		}) ");
}*/
//echo "console.log(\"".$idLayer."\")";

/*$callsGrid->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 all available numbers'],
	        	 	[3,' show all disabled numbers']
	        	 	
	        	  ]
	    }),
	   	 valueField: 'filID',
	   	 value: '2',
	   	 displayField: 'displayText',
	   	 listeners: {
	   	 	select : function(combo,rec) {
	   	 		$callsGrid.ComboNumberFilter = rec.get('filID');
	   	 		$callsGrid.getStore().reload({params:{ hiddenVars:$callsGrid.hiddenVars.join(), ComboNumberFilter: rec.get('filID'), ComboLayer: $callsGrid.ComboLayer, ComboImportFilter: $callsGrid.ComboImportFilter } } );
	   	 	}
	   	 }
		}) ");*/

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

$callsGrid->addTbarItem("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) {
	   	 		$callsGrid.ComboImportFilter = rec.get('filID');
	   	 		$callsGrid.getStore().reload({params:{ hiddenVars:$callsGrid.hiddenVars.join(), ComboNumberFilter: $callsGrid.ComboNumberFilter, ComboLayer: $callsGrid.ComboLayer, ComboImportFilter: rec.get('filID')  } } );
	   	 	}
	   	 }
		}) ");

unset($importSeq);*/

$callsGrid->addExportButton('Export','RMicon_export',array(),false);

echo $callsGrid->createGrid();

if ($defaultColumnVisible) echo implode(" ",$defaultColumnVisible);

echo "//array that stores which vars are hidden and which not
$callsGrid.hiddenVars = new Array();

$callsGrid.ComboLayer = 0;
$callsGrid.ComboNumberFilter = 2;



$callsGrid.getColumnModel().on('hiddenchange',function(col,ind,hidden){
			var tmp = new Array();
			if(col.config[ind].isVar)
			{
				if(hidden) $callsGrid.hiddenVars.push( col.config[ind].name);
				else  $callsGrid.hiddenVars.remove(col.config[ind].name) ;
			}
		    if ( $callsGrid.IgnoreColumnHide == 0 ) $callsGrid.getStore().reload({params:{ hiddenVars:$callsGrid.hiddenVars.join() , ComboLayer: $callsGrid.ComboLayer , ComboNumberFilter: $callsGrid.ComboNumberFilter  } } ); 
			
		});";



echo "mainTabPanel.add({
		id:'$tabId',
		iconCls:'RMicon_call_statistics',
		title:'Call statistics - $projName',
		closable:true,
		layout:'vbox',
		items: [$callsGrid]
}).show();";

?>