<?php

	$GLOBALS['db'] = new MysqlManager();
	$GLOBALS['db']->connect();

	global $mod_strings;
//***********************************************************************************************************************//

	function returnErrorData() {
		header("Content-type: image/png");
		if(isset($_GET['imgWidth']) && $_GET['imgWidth'] != '') $imgWidth = intval($_GET['imgWidth']); else $imgWidth = 600;
		if(isset($_GET['imgHeight']) && $_GET['imgHeight'] != '') $imgHeight = intval($_GET['imgHeight']); else $imgHeight = 600;
		$im = @imagecreate($imgWidth, $imgHeight)
			or die("Cannot Initialize new GD image stream");
		$background_color = imagecolorallocate($im, 255, 255, 255);
		$text_color = imagecolorallocate($im, 100, 100, 100);
		$grey = imagecolorallocate($im, 135, 135, 135);
		imagerectangle($im, 0, 0, $imgWidth-1, $imgHeight-1, $grey);
		global $mod_strings;
		imagestring($im, 7, 20, 20,  translate('LBL_ECMCALLS_NO_DATA', 'Charts'), $text_color);
		//imagettftext($im, 18, 20, 20, 18, $text_color, "CENTURY.TTF", $mod_strings['LBL_ECMCALLS_NO_DATA']);
		imagepng($im);
		imagedestroy($im);
		die();
	}

	// ecmcall_id, calldate, phone
	
	function getUserData($id, $options, $type) {
		$data = array();
		$query = "SELECT `user_name`, `phone_work`, `phone_mobile`, `phone_home`, `phone_other`, `phone_fax`,`first_name`,`last_name` FROM `users` WHERE `id`='$id' LIMIT 1";
		$name = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($query));
		if     ($name['phone_work'] != '') $name['phone'] = 'phone_work';
		elseif ($name['phone_mobile'] != '') $name['phone'] = 'phone_mobile';
		elseif ($name['phone_home'] != '') $name['phone'] = 'phone_home';
		elseif ($name['phone_other'] != '') $name['phone'] = 'phone_other';
		elseif ($name['phone_fax'] != '') $name['phone'] = 'phone_fax';
		
		$phone = $name[$name['phone']];
		

		
		if     ($name['phone_work'] != '' && strlen($phone) > strlen($name['phone_work'])) $phone = $name['phone_work'];
		elseif ($name['phone_mobile'] != '' && strlen($phone) > strlen($name['phone_mobile'])) $phone = $name['phone_mobile'];
		elseif ($name['phone_home'] != '' && strlen($phone) > strlen($name['phone_home'])) $phone = $name['phone_home'];
		elseif ($name['phone_other'] != '' && strlen($phone) > strlen($name['phone_other'])) $phone = $name['phone_other'];
		elseif ($name['phone_fax'] != '' && strlen($phone) > strlen($name['phone_fax'])) $phone = $name['phone_fax'];	
		
		if($options['pbuts_show_numbers'] == 1) $name['user_name'] .= "\n(".$phone.')';

		//die();

			$query  = "SELECT DISTINCT `cdr`.`calldate`, `cdr`.`src`, `cdr`.`duration`, `cdr`.`billsec` ";
			$query .= "FROM `cdr`, `ecmcalls_beans` AS `eb` ";
			$query .= "WHERE `cdr`.`id`=`eb`.`ecmcall_id` ";
			$query .= "AND `eb`.`bean_id`='$id' ";
			
			if($type == "outgoing")
				$query .= "AND ((LPAD(`eb`.`src`,50,'0')=LPAD(`cdr`.`src`,50,'0')) OR (LPAD(`eb`.`src`,50,'0')=LPAD(`cdr`.`dcontext`,50,'0'))) ";
			else
			if($type == "incoming")
				$query .= "AND (LPAD(`eb`.`src`,50,'0')=LPAD(`cdr`.`dst`,50,'0')) ";

			$where = '';
			
			
			if($options['pbuts_date_select'] == 'THIS_DAY' || $options['pbuts_date_select'] == 'LAST_DAY') {
				require_once('modules/EcmCalls/TimeDateC.php');				
				$tdc = new TimeDateC();
				$td = $tdc->queryFilter($options['pbuts_date_select']);

				if($options['pbuts_date_select'] == 'LAST_DAY') {
					$td = $td['end'];
				} elseif($options['pbuts_date_select'] == 'THIS_DAY') {
					$td = $td['begin'];
					//convert date
					global $timedate, $timezones;
					require_once('modules/EcmCalls/TimeDateC.php');
					$tdc = new TimeDateC();
					$td = $tdc->handle_offset($td, $tdc->get_db_date_time_format(), true);			
				}
				$td = substr($td,0,-9);
				$options['pbuts_date'] = $td;
			}
					
			$time_to = '00:00:00'; 
			if(isset($options['pbuts_time_to']) && $options['pbuts_time_to'] != '') {
				$time_to = $options['pbuts_time_to'];
				$pbuts_date = $options['pbuts_date'];
				if($time_to == '24:00') $time_to = '23:59:59'; else $time_to .= ':00';
				$time_to = $pbuts_date.' '.$time_to;
				//convert date
				global $timedate, $timezones;
				require_once('modules/EcmCalls/TimeDateC.php');
				$tdc = new TimeDateC();
				$time_to = $timedate->handle_offset($time_to, $timedate->get_db_date_time_format(), false);			
				$time_to = $tdc->handle_offset($time_to, $tdc->get_db_date_time_format(), true);			
			}

			$time_from = '00:00:00';
			if(isset($options['pbuts_time_from']) && $options['pbuts_time_from'] != '') {
				$time_from = $options['pbuts_time_from'];
				$pbuts_date = $options['pbuts_date'];
				if($time_from == '24:00') $time_from = '23:59:59'; else $time_from .= ':00';
				$time_from = $pbuts_date.' '.$time_from;
				
				//convert date
				global $timedate, $timezones;
				require_once('modules/EcmCalls/TimeDateC.php');
				$tdc = new TimeDateC();
				$time_from = $timedate->handle_offset($time_from, $timedate->get_db_date_time_format(), false);			
				$time_from = $tdc->handle_offset($time_from, $tdc->get_db_date_time_format(), true);			
			}
			
			//var_dump($time_from);
			//var_dump($time_to);
			//die();
						
			if(isset($options['pbuts_date']) && $options['pbuts_date'] != '') {
				if($where != '') $where .= "AND ";
				$where .= "`cdr`.`calldate` >= '$time_from' AND `cdr`.`calldate` <= '$time_to' ";
			}
			
			
			$query .= 'AND '.$where;
			$results = $GLOBALS['db']->query($query);
			
			if(is_resource($results)) {

				$calls = array();
				while($row = $GLOBALS['db']->fetchByAssoc($results)) $calls[] = $row;
				
				$data_tmp = array();
				$data_tmp['values']['<=60']['x'] = array();
				$data_tmp['values']['>60']['x'] = array();
				foreach($calls as $value) {
					$date_ = substr($value['calldate'],0,-3);
					$dd = split(" ",$date_);
					$dd[0] = str_replace("-", "", $dd[0]);
					$dd[1] = split(":",$dd[1]);
					$dur = intval($options['pbuts_watch_seconds']);
					if($options['pbuts_watch'] == 'duration') {
						if(intval($value['duration']) <= $dur) $kk = '<=60'; else $kk = '>60';
					} else {
						if(intval($value['billsec']) <= $dur) $kk = '<=60'; else $kk = '>60';					
					}
					$yyy =  intval($dd[1][0])*60+intval($dd[1][1]);
					if(!isset($yax)) $ymax = $yyy; elseif($yyy > $ymax) $ymax = $yyy;
					if(!isset($ymin)) $ymin = $yyy; elseif($yyy < $ymin) $ymin = $yyy;
					$data_tmp['values'][$kk]['y'][] = $yyy;
				}
				
				if(count($data_tmp['values']['<=60']['y']) > 0 || count($data_tmp['values']['>60']['y']) > 0) {
					$data = $data_tmp;
					$name['user_name']=iconv("utf-8","iso-8859-2",$name['first_name']."\n".$name['last_name']."\n(".$name['phone_work'].")");
					$data['name'] = $name['user_name'];
					$data['ymin'] = $ymin;
					$data['ymax'] = $ymax;
					$data['count'] = count($data);
				}
				//print_r($data);
			}
		return $data;
	}

//**********************************************************************************************************************//




	global $current_user;
	$options = $_SESSION['EcmCallsChart'][$_REQUEST['chartName']][$current_user->id];

	if(isset($_GET['imgWidth']) && $_GET['imgWidth'] != '') $imgWidth = intval($_GET['imgWidth']); else $imgWidth = 600;
	if(isset($_GET['imgHeight']) && $_GET['imgHeight'] != '') $imgHeight = intval($_GET['imgHeight']); else $imgHeight = 600;
	
	if(!is_array($options)) return; 
	
	
	//function getUserPthones

	//print_r($options);
	//die();
	


	include ("include/jpgraph/1.26/src/jpgraph.php"); 
	include ("include/jpgraph/1.26/src/jpgraph_scatter.php"); 


	$graph = new Graph($imgWidth,$imgHeight);

	
	$yaxis = array();
	for($i=0; $i<=24*60; $i+=1) $yaxis[intval(sprintf("%02d%02d",$i/60,$i%60))] = sprintf("%02d:%02d",$i/60,$i%60);
	
	$colors = array('red', 'blue', 'yellow', 'green', 'white', 'brown', 'orange');


$yLabels = array();	$yLabels[0] = ' ';
$users_ = array();
$users_['start'] = array('name' => ' ', 'lp' => 0);
if($options['pbuts_type'] == 'incoming' || 	$options['pbuts_type'] == 'both') {

	$data1 = array();
	$yLc = 1;
	foreach($options['pbuts_users'] as $key => $user_id) {
//for($powiel=0; $powiel<5; $powiel++){
		$data_tmp = getUserData($user_id, $options, 'incoming');
		if(is_array($data_tmp) && count($data_tmp) > 0) { 
			if(!isset($users_[$user_id])) $users_[$user_id] = array('name' => $data_tmp['name'], 'lp' => count($users_));
			$data_tmp['values']['<=60']['x'] = array_pad($data_tmp['values']['<=60']['x'], count($data_tmp['values']['<=60']['y']), $users_[$user_id]['lp']);
			$data_tmp['values']['>60']['x'] = array_pad($data_tmp['values']['>60']['x'], count($data_tmp['values']['>60']['y']), $users_[$user_id]['lp']);
			$data1[] = $data_tmp;
			$yLabels[$yLc++] = $data_tmp['name'];
			if(!isset($ymin)) $ymin = $data_tmp['ymin']; elseif($data_tmp['ymin'] < $ymin) $ymin = $data_tmp['ymin'];
			if(!isset($ymax)) $ymax = $data_tmp['ymax']; elseif($data_tmp['ymax'] > $ymax) $ymax = $data_tmp['ymax'];		
		}
//}
	}
	
	if(count($data1) > 0) {
	$less60legend = false;
	$more60legend = false;
		$sp = array();
		foreach($data1 as $key => $value) {
			if(count($value['values']['<=60']['x']) > 0) {
				$sp['<=60'][$key] = new ScatterPlot($value['values']['<=60']['x'],$value['values']['<=60']['y']);
				$sp['<=60'][$key]->mark->SetType(MARK_FILLEDCIRCLE);
				$sp['<=60'][$key]->mark->SetFillColor('red');
				$sp['<=60'][$key]->mark->SetWidth(5);
				if(!$less60legend) {
					$less60legend = true;
					$sp['<=60'][$key]->SetLegend($mod_strings['LBL_INCOMING_LESS_THAN'].intval($options['pbuts_watch_seconds']).'s');
				}
				$graph->Add($sp['<=60'][$key]);
			}
			if(count($value['values']['>60']['x']) > 0) {
				$sp['>60'][$key] = new ScatterPlot($value['values']['>60']['x'],$value['values']['>60']['y']);
				$sp['>60'][$key]->mark->SetType(MARK_FILLEDCIRCLE);
				$sp['>60'][$key]->mark->SetFillColor('blue');
				$sp['>60'][$key]->mark->SetWidth(5);
				if(!$more60legend) {
					$more60legend = true;
					$sp['>60'][$key]->SetLegend($mod_strings['LBL_INCOMING_MORE_THAN'].intval($options['pbuts_watch_seconds']).'s');
				}
				$graph->Add($sp['>60'][$key]);
			}
		}
	}
} //echo "\n";
if($options['pbuts_type'] == 'both' || 	$options['pbuts_type'] == 'outgoing') {
	$data2 = array();
	$yLc = 1;
	foreach($options['pbuts_users'] as $key => $user_id) {
//for($powiel=0; $powiel<5; $powiel++){
		$data_tmp = getUserData($user_id, $options, 'outgoing');
		if(is_array($data_tmp) && count($data_tmp) > 0) { 
			if(!isset($users_[$user_id])) $users_[$user_id] = array('name' => $data_tmp['name'], 'lp' => count($users_));
			$data_tmp['values']['<=60']['x'] = array_pad($data_tmp['values']['<=60']['x'], count($data_tmp['values']['<=60']['y']), $users_[$user_id]['lp']);
			$data_tmp['values']['>60']['x'] = array_pad($data_tmp['values']['>60']['x'], count($data_tmp['values']['>60']['y']), $users_[$user_id]['lp']);
			$data2[] = $data_tmp;
			$yLabels[$yLc++] = $data_tmp['name'];
			if(!isset($ymin)) $ymin = $data_tmp['ymin']; elseif($data_tmp['ymin'] < $ymin) $ymin = $data_tmp['ymin'];
			if(!isset($ymax)) $ymax = $data_tmp['ymax']; elseif($data_tmp['ymax'] > $ymax) $ymax = $data_tmp['ymax'];		
		}
//}
	}
	
	if(count($data2) > 0) {
	$less60legend = false;
	$more60legend = false;
		$sp = array();
		foreach($data2 as $key => $value) {
			if(count($value['values']['<=60']['x']) > 0) {
				$sp['<=60'][$key] = new ScatterPlot($value['values']['<=60']['x'],$value['values']['<=60']['y']);
				$sp['<=60'][$key]->mark->SetType(MARK_UTRIANGLE);
				//$sp['<=60'][$key]->mark->SetType(MARK_IMG,'modules/Home/Dashlets/MyEcmCallsMoreDashlets/green.gif',1);
				$sp['<=60'][$key]->mark->SetFillColor('red');
				$sp['<=60'][$key]->mark->SetWidth(10);
				if(!$less60legend) {
					$less60legend = true;
					$sp['<=60'][$key]->SetLegend($mod_strings['LBL_OUTGOING_LESS_THAN'].intval($options['pbuts_watch_seconds']).'s');
				}
				$graph->Add($sp['<=60'][$key]);
			}
			if(count($value['values']['>60']['x']) > 0) {
				$sp['>60'][$key] = new ScatterPlot($value['values']['>60']['x'],$value['values']['>60']['y']);
				$sp['>60'][$key]->mark->SetType(MARK_UTRIANGLE);
				//$sp['<=60'][$key]->mark->SetType(MARK_IMG,'modules/Home/Dashlets/MyEcmCallsMoreDashlets/red.gif',1);
				$sp['>60'][$key]->mark->SetFillColor('blue');
				$sp['>60'][$key]->mark->SetWidth(10);
				if(!$more60legend) {
					$more60legend = true;
					$sp['>60'][$key]->SetLegend($mod_strings['LBL_OUTGOING_MORE_THAN'].intval($options['pbuts_watch_seconds']).'s');
				}
				$graph->Add($sp['>60'][$key]);
			}
		}
	}
}
$users_['end'] = array( 'name' => ' ', 'lp' => count($users_));
//die();

$yLabels = array();
foreach($users_ as $key => $value) $yLabels[$value['lp']] = $value['name'];
	if(count($data1)==0 && count($data2)==0) returnErrorData();
	
	$d1 = new ScatterPlot(array(0),array($ymin));
	$d1->mark->SetType(MARK_FILLEDRECTANGLE);
	$d1->mark->SetFillColor('green');
	$d1->mark->SetWidth(10);
	$graph->Add($d1);

	$d2 = new ScatterPlot(array(count($users_)-1),array($ymin));
	$d2->mark->SetType(MARK_FILLEDRECTANGLE);
	$d2->mark->SetFillColor('green');
	$d2->mark->SetWidth(10);
	$graph->Add($d2);	
	//var_dump(count($data));
	//die();

			if($options['pbuts_date_select'] == 'THIS_DAY' || $options['pbuts_date_select'] == 'LAST_DAY') {
				require_once('modules/EcmCalls/TimeDateC.php');				
				$tdc = new TimeDateC();
				$td = $tdc->queryFilter($options['pbuts_date_select']);

				if($options['pbuts_date_select'] == 'LAST_DAY') {
					$td = $td['end'];
				} elseif($options['pbuts_date_select'] == 'THIS_DAY') {
					$td = $td['begin'];
					//convert date
					global $timedate, $timezones;
					require_once('modules/EcmCalls/TimeDateC.php');
					$tdc = new TimeDateC();
					$td = $tdc->handle_offset($td, $tdc->get_db_date_time_format(), true);			
				}
				$td = substr($td,0,-9);
				$date = $td;
			}


	
	$graph->SetMarginColor('white');
	$graph->SetScale("linlin");
	$sTitle = ",  ".(isset($date) && $date != '' ? $date : $options['pbuts_date']).'  '.$options['pbuts_time_from'].' - '.$options['pbuts_time_to'];
	$graph->title->Set($options['title'].$sTitle);
	$graph->title->SetFont(FF_FONT1,FS_BOLD);
	$graph->SetMargin(80,30,40,130);

	$graph->xgrid->Show();
	$graph->xgrid->SetColor('gray@0.5');
	$graph->ygrid->SetColor('gray@0.5');

	$graph->SetFrame(true,'gray@0.3');
	
$ymin = intval($ymin/5)*5;
$ymax = intval($ymax/5)*5;

	$xLabels = array();
	$xTF = split(":",$options['pbuts_time_from']);
	$xTFrom = $ymin-15;//intval($xTF[0])*60+intval($xTF[1]);
	$xTT = split(":",$options['pbuts_time_to']);
	$xTTo = $ymax+15;//intval($xTT[0])*60+intval($xTT[1]);
	$tick = abs($xTTo-$xTFrom); if($tick == 0) $tick = 15;
	$tick = intval($tick/60);
	//var_dump($tick);
	if($tick/5 > 4) $tick = 60; 
	elseif($tick/5 >= 3) $tick = 45; 
	elseif($tick/5 >= 2) $tick = 30; 
	elseif($tick/5 >= 1) $tick = 30;
	elseif($tick%5 == 0) $tick = intval(($tick/5))*10; else $tick = intval(($tick/5))*10 + 10;
	if(abs($xTFrom-$xTTo) < 60) $tick = 2;
	if($tick == 0) $tick = 5;
	//var_dump(intval($tick)); die();
	for( $i = 0, $j=$xTFrom; $i <= abs($xTTo-$xTFrom); $i+=$tick, $j+=$tick) {
		$xLabels[] = sprintf("%02d:%02d",$j/60,$j%60);
		$xTickPositions[] = $j;
	}
	//print_r($xTickPositions);
	//print_r($xLabels);
	//die();
	$graph->xaxis->SetTickPositions($xTickPositions,null,$xLabels);
	$graph->xaxis->SetLabelAngle(90);

	

	$yTickPositions = array();
	foreach($yLabels as $key=>$value) $yTickPositions[] = count($yTickPositions);
	
	if(count($yLabels) == 1) {
		$yTickPositions[] = count($yTickPositions);
		$yLabels[] = '';
	}
	$graph->yaxis->SetTickPositions($yTickPositions,null,$yLabels);
	//print_r($yTickPositions);
	//print_r($yLabels);
	//die();
//$graph->legend->SetLayout(LEGEND_HOR);
$graph->legend->Pos(0.2,0.97,"left","bottom");
	$graph->Stroke();

?>