<?php
require_once "app/class-reports.php";
require_once "includes/autoload.dist.php";
use Jaspersoft\Client\Client;

/**
 * Reports Context
 *
 * Context for Reports managment
 *
 * @author nh - Advantis Solutions
 * @version 1.0.1
 * @package Backend\Reports
 */
class context_reports extends context {
	public $contextname = "reports";
	
	/**
	 * Constructor & Authorization
	 */
	function context_reports() {
		main::check_auth_session ();
	}
	
	/**
	 * Default action
	 */
	function index() {
		$em = new EntityManager ( Reports::LISTVIEW, 'STATISTIC' );
		$list = $em->load ( 'languageid=:langid', array(':langid' => Session::get_language ()->id )  );
		$country = new EntityManager ( Reports::COUNTRIES, 'STATISTIC' );
		$country_list = $country->load ( 'languageid=:langid' , array(':langid' => Session::get_language ()->id) );
		$this->screen ( $this->contextname . "/index", array (
				'list' => $list,
				'countries' => $country_list 
		) );
	}
	
	/**
	 * Show report by request
	 */
	function showReport() {
		$c = new Client ( JSP_SERVER, JSP_USER, JSP_PASSWORD );
		$reportValues = array ();
		if (! empty ( filter_input_array ( INPUT_POST ) )) {
			foreach ( filter_input_array ( INPUT_POST ) as $key => $value ) {
				$reportValues [$key] = $value;
			}
			$file_type = $reportValues ['output'];
			$report_type = $reportValues ['reportType'];
			
			$controls = array (
					'year_ini' => array (
							$reportValues ['year_ini'] 
					),
					'year_fin' => array (
							$reportValues ['year_fin'] 
					),
					'lang_id' => array (
							$reportValues ['lang_id'] 
					),
					'indicator_id' => array (
							$reportValues ['indicatorID'] 
					),
					'country_id' => array (
							$reportValues ['country'] 
					),
					'finalrelease' => array (
							$reportValues ['finalRelease'] 
					) 
			);
			
			$report = $c->reportService ()->runReport ( JSP_REPOSITORY . $report_type, $file_type, null, null, $controls );
			if ($file_type == 'pdf') {
				$file_name = 'Reports.pdf';
				header ( 'Content-type: application/pdf' );
				header ( "Content-Disposition: attachment; filename=$file_name" );
				header ( "Pragma: no-cache" );
				header ( "Expires: 0" );
			} elseif ($file_type == 'xls') {
				$file_name = 'Reports.xls';
				header ( "Content-Type: application/vnd.ms-excel" );
				header ( "Content-Disposition: attachment; filename=$file_name" );
				header ( "Pragma: no-cache" );
				header ( "Expires: 0" );
			} else {
				header ( 'Content-Type: text/html' );
			}
			echo $report;
		}
	}
}