<?php

class StatsController extends Controller
{
  public function getRecentTransitsDay()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getToday());  
  }
  
  public function getRecentTransitsWeek()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfWeek());  
  }
  
  public function getRecentTransitsMonth()
  {
    return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfMonth());  
  }
  
  public function getRecentTransits($date)
  {
    $result = query('SELECT SUM(Counter) AS cnt FROM statstable IGNORE INDEX(Index_gate) WHERE StartDateTime >= :tm', array(':tm'=>$date));
    if(is_numeric($result->cnt)) {
      return $result->cnt;
    }
    else {
      return 0;
    }
  }
  
  protected function beforeAction($event)
  {
    return parent::beforeAction($event);
  }
  
  public function actionStatusBox()
  { 
    return $this->renderPartial('statusBox');
  }
  
  public function actionIndex()
  {
    access_denied_check("statistics");
    $gates = Gate::getAllGates();
    $this->render('index', array('gates' => $gates));
  }

  public function actionDangerousGoods()
  {
    access_denied_check("statistics");
    $gates = Gate::getAllGates();
  	$this->render('dangerousGoods/index', array('gates' => $gates));
  }
  
  public function actionFilter(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime)
  {
    access_denied_check("statistics");
    $statsQuery = new StatsQuery();
    $dataProvider = $statsQuery->getStatsData(
      array(
        'vehiclesClass'		=> $vehiclesClass,
        'gates'         	=> $gates,
        'startTimestamp' 	=> $startTimestamp,
        'endTimestamp'   	=> $endTimestamp,
      	'minSpeed'      	=> $minSpeed,
        'maxSpeed'      	=> $maxSpeed,
        'granularity'   	=> $granularity,
  		'startTime' 		=> $startTime,
  		'endTime'   		=> $endTime,
      )
    );

    $graphData = VehicleStatGraphEncoder::encode($dataProvider->getData(), 'StartDateTime', 'Counter', $granularity);
    $this->renderPartial('_results', array('dataProvider' => $dataProvider, 'graphData' => $graphData));
  }
  
  public function actionEventsManagement()
  {
  	access_denied_check("statistics");
  	
  	access_denied_check("statistics_events_management");
  	
  	set_time_limit(3000);
  	
  	$violationsCountByTimespanStatsData = NULL;
  	$approvedViolationsCountByTimespanStatsData = NULL;
  	$invalidViolationsCountByTimespanStatsData = NULL;
  	$pendingViolationsCountByTimespanStatsData = NULL;
  	$exportedEventsCountByTimespanStatsData = NULL;
  	$violationsCountByGate = NULL;
  	$approvedViolationsCountByGate = NULL;
  	$invalidViolationsCountByGate = NULL;
  	$exportedEventsCountByGate = NULL;
  	
  	$gateModel = Gate::model();
  	$gates = $gateModel->findAll();
  	
  	$eventsStatisticsSearchForm = new EventsStatisticsSearchForm();
  	if (isset($_POST['EventsStatisticsSearchForm'])) {
  		
  		$eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);
  		
  		$searchFilters = array();
  		
  		$validationResult = $eventsStatisticsSearchForm->validate();
  		if (!$validationResult) {
  			
  			$this->render("eventsManagement/index",
  				array(
  					'gates' => $gates,
  					'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
  					'validationErrors' => $eventsStatisticsSearchForm->getErrors()
  				)
  			);
  			
  			return;
  			
  		}
  		
  		$startDateTime = DateTime::createFromFormat(
  			getFormat_DateTime(),
  			$eventsStatisticsSearchForm->startDateTime
  		);
  		
  		$endDateTime = DateTime::createFromFormat(
  			getFormat_DateTime(),
  			$eventsStatisticsSearchForm->endDateTime
  		);
  		
  		if (!empty($eventsStatisticsSearchForm->gates)) {
  			
  			$searchFilters = array_merge($searchFilters,
  				array('gates' => $eventsStatisticsSearchForm->gates)
  			);
  			
  		}
  		
  		if (!empty($eventsStatisticsSearchForm->startTimeSlot)
  			&& !empty($eventsStatisticsSearchForm->endTimeSlot)) {
  					
  			$startTimeSlot = DateTime::createFromFormat(
  				getFormat_Time(),
  				$eventsStatisticsSearchForm->startTimeSlot
  			);
  					
  			$endTimeSlot = DateTime::createFromFormat(
  				getFormat_Time(),
  				$eventsStatisticsSearchForm->endTimeSlot
  			);
  					
  			$searchFilters = array_merge($searchFilters,
  				array('timeSlot' => array(
  						'startTimeSlot' => $startTimeSlot,
  						'endTimeSlot' => $endTimeSlot
  					)
  				)
  			);
  					
  		}
  	
  		$eventsStatistics = EventsStatistics::model();
  		
	  	$violationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
	  			$startDateTime, $endDateTime, $searchFilters);
	  	
	  	$approvedViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
	  		$startDateTime, $endDateTime, array_merge($searchFilters,
	  			array(
	  				'approvedViolations' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$invalidViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
	  		$startDateTime, $endDateTime, array_merge($searchFilters,
	  			array(
	  				'invalidViolations' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$pendingViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
	  		$startDateTime, $endDateTime, array_merge($searchFilters,
	  			array(
	  				'pendingViolations' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$exportedEventsCountByTimespanStatsData = $eventsStatistics->getEventsCountByOccurenceDateTime(
	  		$startDateTime, $endDateTime, array_merge($searchFilters,
	  			array(
	  				'exportedEvents' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$violationsCountByGate = $eventsStatistics->getViolationsCountByGate(
	  		array_merge($searchFilters,
	  			array(
	  				'eventStartDateTime' => $startDateTime,
	  				'eventEndDateTime' => $endDateTime
	  			)
	  		)
	  	);
	  	
	  	$approvedViolationsCountByGate = $eventsStatistics->getViolationsCountByGate(
	  		array_merge($searchFilters,
	  			array(
	  				'eventStartDateTime' => $startDateTime,
	  				'eventEndDateTime' => $endDateTime,
	  				'approvedViolations' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$invalidViolationsCountByGate = $eventsStatistics->getViolationsCountByGate(
	  		array_merge($searchFilters,
	  			array(
	  				'eventStartDateTime' => $startDateTime,
	  				'eventEndDateTime' => $endDateTime,
	  				'invalidViolations' => TRUE
	  			)
	  		)
	  	);
	  	
	  	$exportedEventsCountByGate = $eventsStatistics->getEventsCountByGate(
	  			array_merge($searchFilters,
	  					array(
							'eventStartDateTime' => $startDateTime,
	  						'eventEndDateTime' => $endDateTime,
	  						'exportedEvents' => TRUE
	  					)
	  			)
	  	);
	  	
  	}
  	
  	$this->render("eventsManagement/index",
  		array(
  			'gates' => $gates,
  			'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
  			'violationsCountByTimespanStatsData' => $violationsCountByTimespanStatsData,
  			'approvedViolationsCountByTimespanStatsData' => $approvedViolationsCountByTimespanStatsData,
  			'invalidViolationsCountByTimespanStatsData' => $invalidViolationsCountByTimespanStatsData,
  			'pendingViolationsCountByTimespanStatsData' => $pendingViolationsCountByTimespanStatsData,
  			'exportedEventsCountByTimespanStatsData' => $exportedEventsCountByTimespanStatsData,
  			'violationsCountByGate' => $violationsCountByGate,
  			'approvedViolationsCountByGate' => $approvedViolationsCountByGate,
  			'invalidViolationsCountByGate' => $invalidViolationsCountByGate,
  			'exportedEventsCountByGate' => $exportedEventsCountByGate
  		)
  	);
  	
  }
  
  public function actionEventsManagementExport()
  {

  	access_denied_check("statistics");
  	
  	access_denied_check("statistics_events_management");
  	
  	header('Set-Cookie: fileDownload=true; path=/;');
  	
  	set_time_limit(60*60*1);
  	
  	$eventsStatisticsSearchForm = new EventsStatisticsSearchForm();
  	
  	$eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);
  	
  	$searchFilters = array();
  	
  	$validationResult = $eventsStatisticsSearchForm->validate();
  	if (!$validationResult) {
  		
  		throw new CHttpException(400, Yii::t('app', 'Error While Validating FORM'));
  		  			
  	}
  
  	$startDateTime = DateTime::createFromFormat(
  		getFormat_DateTime(),
  		$eventsStatisticsSearchForm->startDateTime
  	);
  		
  	$endDateTime = DateTime::createFromFormat(
  		getFormat_DateTime(),
  		$eventsStatisticsSearchForm->endDateTime
  	);
  	
  	$searchFilters['eventStartDateTime'] = $startDateTime;
  	$searchFilters['eventEndDateTime'] = $endDateTime;
  	
  	if (!empty($eventsStatisticsSearchForm->gates)) {
  			
  		$searchFilters = array_merge($searchFilters,
  			array('gates' => $eventsStatisticsSearchForm->gates)
  		);
  		
  	}
  	
  	if (!empty($eventsStatisticsSearchForm->startTimeSlot)
  		&& !empty($eventsStatisticsSearchForm->endTimeSlot)) {
  					
  		$startTimeSlot = DateTime::createFromFormat(
  			getFormat_Time(),
  			$eventsStatisticsSearchForm->startTimeSlot
  		);
  					
		$endTimeSlot = DateTime::createFromFormat(
			getFormat_Time(),
			$eventsStatisticsSearchForm->endTimeSlot
		);
  					
		$searchFilters = array_merge($searchFilters,
			array('timeSlot' => array(
					'startTimeSlot' => $startTimeSlot,
					'endTimeSlot' => $endTimeSlot
				)
			)
		);
  					
	}
	
	$eventsStatistics = EventsStatistics::model();
	
	$violationsManagementStatisticsByGatesCSV = $eventsStatistics->getViolationsManagementByGateStatisticsCSV($searchFilters);
  	
	$csv = new ECSVExport($violationsManagementStatisticsByGatesCSV);
  	$content = $csv->toCSV();
  	
  	$fileName = "Events_Management_By_Gates_From_";
  	$fileName.= $startDateTime->format("Y_m_d_H_i_s");
  	$fileName.= "_To_";  			
  	$fileName.= $endDateTime->format("Y_m_d_H_i_s");
  	$fileName.= ".csv";
  	
  	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
  	
  	exit();
  }
  
  public function actionOperatorsStatistics()
  {
  	access_denied_check("statistics");
  	
  	access_denied_check("statistics_operators_statistics");
  	
  	set_time_limit(3000);
  	
  	$gateModel = Gate::model();
  	
  	$gates = $gateModel->findAll();
  	
  	$approvedViolationsCountByTimespanStatsData = NULL;
  	$invalidViolationsCountByTimespanStatsData = NULL;
  	$usersApprovedViolationsCountByTimespanStatsData = NULL;
  	$usersInvalidViolationsCountByTimespanStatsData = NULL;
  	$validationDecisionsByTimespanStatsData = NULL;
  	$usersValidationDecisionsByTimespanStatsData = NULL;
  	
  	$eventsStatisticsSearchForm = new EventsStatisticsSearchForm();
  	if (isset($_POST['EventsStatisticsSearchForm'])) {
  		
  		$eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);
  		
  		$searchFilters = array();
  		
  		$validationResult = $eventsStatisticsSearchForm->validate();
  		if (!$validationResult) {
  			
  			$this->render("operatorsStatistics/index",
  				array(
  					'gates' => $gates,
  					'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
  					'validationErrors' => $eventsStatisticsSearchForm->getErrors()
  				)
  			);
  			
  			return;
  			
  		}
  		
  		$startDateTime = DateTime::createFromFormat(
  			getFormat_DateTime(),
  			$eventsStatisticsSearchForm->startDateTime
  		);
  		
  		$endDateTime = DateTime::createFromFormat(
  			getFormat_DateTime(),
  			$eventsStatisticsSearchForm->endDateTime
  		);
  		
  		if (!empty($eventsStatisticsSearchForm->gates)) {
  			
  			$searchFilters = array_merge($searchFilters,
  				array('gates' => $eventsStatisticsSearchForm->gates)
  			);
  			
  		}
  		
  		$eventsStatistics = EventsStatistics::model();
  		
  		$approvedViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByValidationDateTime(
  			$startDateTime, $endDateTime, array_merge($searchFilters,
  				array(
  					'approvedViolations' => TRUE
  				)
  			)
  		);
  		
  		$invalidViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByValidationDateTime(
  			$startDateTime, $endDateTime, array_merge($searchFilters,
  				array(
  					'invalidViolations' => TRUE
  				)
  			)
  		);
  		
  		$usersApprovedViolationsCountByTimespanStatsData = $eventsStatistics->getUsersViolationsCountByValidationDateTime(
  			$startDateTime, $endDateTime, array_merge($searchFilters,
  				array(
  					'approvedViolations' => TRUE
  				)
  			)
  		);
  		
  		$usersInvalidViolationsCountByTimespanStatsData = $eventsStatistics->getUsersViolationsCountByValidationDateTime(
  			$startDateTime, $endDateTime, array_merge($searchFilters,
  				array(
  					'invalidViolations' => TRUE
  				)
  			)
  		);
  		
  		$validationDecisionsByTimespanStatsData = $eventsStatistics->getValidationDecisionsByValidationDateTime(
  				$startDateTime, $endDateTime, $searchFilters);
  		
  		$usersValidationDecisionsByTimespanStatsData = $eventsStatistics->getUsersValidationDecisionsByValidationDateTime(
  				$startDateTime, $endDateTime, $searchFilters);
  		
  	}
  	
  	$this->render("operatorsStatistics/index",
  		array(
  			'gates' => $gates,
  			'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
  			'approvedViolationsCountByTimespanStatsData' => $approvedViolationsCountByTimespanStatsData,
  			'usersApprovedViolationsCountByTimespanStatsData' => $usersApprovedViolationsCountByTimespanStatsData,
  			'usersInvalidViolationsCountByTimespanStatsData' => $usersInvalidViolationsCountByTimespanStatsData,
  			'invalidViolationsCountByTimespanStatsData' => $invalidViolationsCountByTimespanStatsData,
  			'validationDecisionsByTimespanStatsData' => $validationDecisionsByTimespanStatsData,
  			'usersValidationDecisionsByTimespanStatsData' => $usersValidationDecisionsByTimespanStatsData
  		)
  	);
  
  }
  
  public function actionExport(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime)
  {
    access_denied_check("statistics");
    header('Set-Cookie: fileDownload=true; path=/');

    set_time_limit(60*60*1);
    
  	$statsQuery = new StatsQuery();
  	$dataProvider = $statsQuery->getStatsData(
  		array(
  			'vehiclesClass'		=> $vehiclesClass,
  			'gates'         	=> $gates,
  			'startTimestamp'	=> $startTimestamp,
  			'endTimestamp'		=> $endTimestamp,
  			'minSpeed'      	=> $minSpeed,
  			'maxSpeed'      	=> $maxSpeed,
  			'granularity'   	=> $granularity,
  			'useJoin'			=> true,
  			'startTime' 		=> $startTime,
  			'endTime'   		=> $endTime,
  		)
  	);
  	
  	$csv = new ECSVExport($dataProvider);
  	$content = $csv->toCSV();
		
  	$startDateTime = new DateTime();
  	$startDateTime->setTimestamp($startTimestamp);
  	
  	$endDateTime = new DateTime();
  	$endDateTime->setTimestamp($endTimestamp);
  	 
  	$startTimeStr = str_replace(":", "_", $startTime);
  	$endTimeStr = str_replace(":", "_", $endTime);
  	 
  	$fileName = "Stats_from_".$startDateTime->format("Y_m_d")."_".$startTimeStr."_to_".$endDateTime->format("Y_m_d")."_".$endTimeStr.".csv";
  	  	
  	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
		
	exit();
  }
    
  public function actionExportDetailed(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime)
  {	
    access_denied_check("statistics");
	header('Set-Cookie: fileDownload=true; path=/');
	
	set_time_limit(60*60*1);
	
	$statsQuery = new StatsQuery();
	$dataProvider = $statsQuery->getStatsData(
		array(
			'vehiclesClass'		=> $vehiclesClass,
			'gates'         	=> $gates,
			'startTimestamp'	=> $startTimestamp,
			'endTimestamp'		=> $endTimestamp,
			'minSpeed'			=> $minSpeed,
			'maxSpeed'			=> $maxSpeed,
			'granularity'		=> $granularity,
			'splitByGate'		=> true,
			'splitByClass'		=> true,
			'useJoin'			=> true,
  			'startTime'			=> $startTime,
  			'endTime'   	 	=> $endTime,
		)
	);
		 
	$csv = new ECSVExport($dataProvider);
	$content = $csv->toCSV();
	
	$startDateTime = new DateTime();
	$startDateTime->setTimestamp($startTimestamp);
		 
	$endDateTime = new DateTime();
	$endDateTime->setTimestamp($endTimestamp);
	
    $startTimeStr = str_replace(":", "_", $startTime);
    $endTimeStr = str_replace(":", "_", $endTime);
  	 
    $fileName = "Stats_from_".$startDateTime->format("Y_m_d")."_".$startTimeStr."_to_".$endDateTime->format("Y_m_d")."_".$endTimeStr.".csv";
				 
	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
	
    exit();
  }	
	
  public function actionDangerousGoodsFilter(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime)
  {
    access_denied_check("statistics");
    $statsQuery = new DangerousGoodsFromEventStatsQuery();
  	$dataProvider = $statsQuery->getStatsData(
  		array(
  			'gates'				=> $gates,
  			'startTimestamp'	=> $startTimestamp,
  			'endTimestamp'		=> $endTimestamp,
  			'startTime' 		=> $startTime,
  			'endTime'   		=> $endTime,
  		)
  	);
  
  	$graphData = DangerousGoodsStatGraphEncoder::encode($dataProvider->getData(), 'kemler', 'Counter');
  	$this->renderPartial('dangerousGoods/_results', array('dataProvider' => $dataProvider, 'graphData' => $graphData));
  }
  
  public function actionDangerousGoodsExport(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime)
  {
    header('Set-Cookie: fileDownload=true; path=/');
  	
    set_time_limit(60*60*1);
    
  	$statsQuery = new DangerousGoodsFromEventStatsQuery();
  	$dataProvider = $statsQuery->getStatsData(
  		array(
  			'gates'				=> $gates,
  			'startTimestamp'	=> $startTimestamp,
  			'endTimestamp'		=> $endTimestamp,
  			'startTime' 		=> $startTime,
  			'splitByGate'		=> true,
  			'useJoin'			=> true,
  	        'endTime'   		=> $endTime,
  			'descriptions'		=> true,
  		)
  	);
  
	$csv = new ECSVExport($dataProvider);
  	$content = $csv->toCSV();
		
  	$startDateTime = new DateTime();
  	$startDateTime->setTimestamp($startTimestamp);
  	
  	$endDateTime = new DateTime();
  	$endDateTime->setTimestamp($endTimestamp);
  	 
  	$startTimeStr = str_replace(":", "_", $startTime);
  	$endTimeStr = str_replace(":", "_", $endTime);
  	 
  	$fileName = "Stats_from_".$startDateTime->format("Y_m_d")."_".$startTimeStr."_to_".$endDateTime->format("Y_m_d")."_".$endTimeStr.".csv";
  	
  	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
		
	exit();
  }
  
  public function actionDangerousGoodsExportDetailed(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime)
  {
    access_denied_check("statistics");
    header('Set-Cookie: fileDownload=true; path=/');
  	
    set_time_limit(60*60*1);
    
  	$statsQuery = new DangerousGoodsFromEventStatsQuery();
  	$dataProvider = $statsQuery->getStatsData(
  		array(
  			'gates'				=> $gates,
  			'startTimestamp'	=> $startTimestamp,
  			'endTimestamp'		=> $endTimestamp,
  			'startTime' 		=> $startTime,
  			'endTime'   		=> $endTime,
  			'descriptions'		=> true,
  			'splitByGate'		=> true,
    	    'splitByHour'		=> true,
  			'useJoin'			=> true,
  		)
  	);
  
  	$csv = new ECSVExport($dataProvider);
  	$content = $csv->toCSV();
		
  	$startDateTime = new DateTime();
  	$startDateTime->setTimestamp($startTimestamp);
  	
  	$endDateTime = new DateTime();
  	$endDateTime->setTimestamp($endTimestamp);
  	
  	$startTimeStr = str_replace(":", "_", $startTime);
  	$endTimeStr = str_replace(":", "_", $endTime);
  	 
  	$fileName = "Stats_from_".$startDateTime->format("Y_m_d")."_".$startTimeStr."_to_".$endDateTime->format("Y_m_d")."_".$endTimeStr.".csv";
  	
  	Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);
  	
  	exit();
  }

}
