<?php

/************************************************************************/
/* DOCEBO LMS - Learning managment system									*/
/* ============================================							*/
/*																			*/
/* Copyright (c) 2005														*/
/* http://www.docebo.com													*/
/*																			*/
/* This program is free software. You can redistribute it and/or modify	*/
/* it under the terms of the GNU General Public License as published by	*/
/* the Free Software Foundation; either version 2 of the License.		*/
/************************************************************************/

if(!defined('IN_DOCEBO')) die('You cannot access this file directly');

/**
 * @version  $Id: class.report_delay_two.php 573 2006-08-23 09:38:54Z fabio $
 * @author	 Fabio Pirovano <fabio [at] docebo [dot] com>
 */

require_once($GLOBALS['where_lms'].'/admin/modules/report/class.report.php');
require_once($GLOBALS['where_lms'].'/lib/lib.course.php');

class Report_DelayTwo extends Report {
	
	var $lang;
	
	function Report_DelayTwo($id_report) {
		$this->lang =& DoceboLanguage::createInstance('ru_report');
		parent::Report($id_report);
	}
	
	function play($jump_url, $back_url, $alluser, $org_chart_subdivision, $start_time, $end_time) {
		
		require_once($GLOBALS['where_framework'].'/lib/lib.form.php');
		require_once($GLOBALS['where_framework'].'/lib/lib.directory.php');
		require_once($GLOBALS['where_framework'].'/class.module/class.directory.php');
		require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
		
		$lang =& DoceboLanguage::createInstance('report');
		
		$page_title = getTitleArea(array(
			str_replace('&', '&amp;', $back_url) => $lang->def('_REPORT'),
			$this->report_name
		), 'report', $lang->def('_ALT_REPORT'));
		
		if($alluser == 1) {
			
			$GLOBALS['page']->add(
				$page_title
				.'<div class="std_block">'
				.getBackUi(str_replace('&', '&amp;', $back_url), $lang->def('_BACK')), 'content');
			$this->show_report($jump_url, true, $org_chart_subdivision, $start_time, $end_time);
			$GLOBALS['page']->add('</div>', 'content');
			return;
		}
		if(isset($_POST['cancelselector'])) {
			
			jumpTo($back_url);
		} elseif(isset($_POST['okselector'])) {
			
			$GLOBALS['page']->add(
				$page_title
				.'<div class="std_block">'
				.getBackUi(str_replace('&', '&amp;', $back_url), $lang->def('_BACK')), 'content');
			$this->show_report($jump_url, false, $org_chart_subdivision, $start_time, $end_time);
			$GLOBALS['page']->add('</div>', 'content');
			return;
		} elseif(isset($_POST['export_cvs'])) {
			
			$this->exportAsCvs($org_chart_subdivision, $start_time, $end_time);
		} else {
			
			// first step load selector 
			require_once($GLOBALS['where_framework'].'/class.module/class.directory.php');
			
			$aclManager = new DoceboACLManager();
			$user_select = new Module_Directory();
			
			if($org_chart_subdivision == 0) {
				
				$user_select->show_user_selector = TRUE;
				$user_select->show_group_selector = TRUE;
			} else {
				
				$user_select->show_user_selector = FALSE;
				$user_select->show_group_selector = FALSE;
			}
			$user_select->show_orgchart_selector = TRUE;
			$user_select->show_orgchart_simple_selector = FALSE;
			$user_select->multi_choice = TRUE;
			
			$user_select->addFormInfo(
				Form::getHidden('start_time', 'start_time', $start_time)
				.Form::getHidden('end_time', 'end_time', $end_time)
				.Form::getHidden('org_chart_subdivision', 'org_chart_subdivision', $org_chart_subdivision)
				.Form::getHidden('alluser', 'alluser', $alluser)
			);
			$user_select->setPageTitle($page_title);
			$user_select->loadSelector(str_replace('&', '&amp;', $jump_url), 
					false, 
					$lang->def('_CHOOSE_USER_FOR_REPORT'), 
					true, 
					true );
		}
		
	}
	
	function show_report($jump_url, $alluser, $org_chart_subdivision, $start_time, $end_time) {
		
		$lang =& DoceboLanguage::createInstance('rd2_report');
		
		$acl_man 		= new DoceboACLManager();
		$course_man 	= new Man_Course();
		
		$user_select 	= new Module_Directory();
		$elem_selected 	= $user_select->getSelection($_POST);
		$user_selected 	=& $acl_man->getAllUsersFromIdst($elem_selected);
		
		if($alluser == 0) {
			$user_select 	= new Module_Directory();
			$elem_selected 	= $user_select->getSelection($_POST);
			$user_selected 	=& $acl_man->getAllUsersFromIdst($elem_selected);
			
		} else {
			
			$user_selected =& $this->getAllUserIdst();
		}
		if($org_chart_subdivision == 1) {
			
			require_once($GLOBALS['where_framework'].'/lib/lib.orgchart.php');
			$org_man 	= new OrgChartManager();
			if($alluser == 1) {
				$elem_selected = $org_man->getAllGroupIdFolder();
			}
			$org_name = $org_man->getFolderFormIdst($elem_selected);
		}
		
		if(empty($user_selected)) {
			
			$GLOBALS['page']->add($lang->def('_NULL_SELECTION'), 'content');
			return;
		}
		$users_info =& $acl_man->getUsers($user_selected);
		
		// Retrive all the course
		$course =& $course_man->getAllCoursesWithMoreInfo();
		if(empty($course)) {
			
			$GLOBALS['page']->add($lang->def('_NULL_COURSE_SELECTION'), 'content');
			return;
		}
		
		// Css
		$GLOBALS['page']->add(
			"\n".'<link href="'.getPathTemplate('lms').'style/report/style_report_delay.css" rel="stylesheet" type="text/css" />'."\n"
		, 'page_head');
		
		// Export as cvs ------------------------------------------------
		$GLOBALS['page']->add(
			Form::openForm('export', $jump_url)
			.Form::openElementSpace('')
			.Form::getHidden('org_chart_subdivision', 'org_chart_subdivision', ( $org_chart_subdivision ?  1 : 0 ))
			.Form::getHidden('start_time', 'start_time', $start_time)
			.Form::getHidden('end_time', 'end_time', $end_time)
			.Form::getHidden('elem_selected', 'elem_selected', urlencode(serialize($elem_selected)))
			.Form::getHidden('user_selected', 'user_selected', urlencode(serialize($user_selected)))
			.form::getButton('export_cvs', 'export_cvs', $lang->def('_CSVEXPORT'), 'export_cvs')
			.Form::closeElementSpace()
			.Form::closeForm()
		, 'content');
		
		if($org_chart_subdivision === 0) {
			
			// find some information
			$query_time ="
			SELECT idUser, idCourse, status, UNIX_TIMESTAMP(date_inscr), UNIX_TIMESTAMP(date_first_access), UNIX_TIMESTAMP(date_complete)
			FROM ".$GLOBALS['prefix_lms']."_courseuser 
			WHERE idUser IN (".implode(',', $user_selected).")";
			if($start_time != '') $query_time .= " AND date_inscr >= '".$start_time."' ";
			if($end_time != '') $query_time .= " AND date_inscr <= '".$end_time."' ";
			
			$this->_printTable($acl_man, $query_time, $course, $users_info);
		} else {
			
			$date_now = $GLOBALS['regset']->databaseToRegional(date("Y-m-d H:i:s")); 
			
			reset($org_name);
			while(list($idst_group, $folder_name) = each($org_name)) {
				
				$GLOBALS['page']->add('<div class="datasummary">'
					.'<b>'.$lang->def('_FOLDER_NAME').' :</b> '.$folder_name['name']
						.( $folder_name['type_of_folder'] == ORG_CHART_WITH_DESCENDANTS ? ' ('.$lang->def('_WITH_DESCENDANTS').')' : '' ).'<br />'
					, 'content');
				if($start_time != '' || $end_time != '') {
					
					$GLOBALS['page']->add('<b>'.$lang->def('_TIME_BELT_2').' :</b> '
						.( $start_time != '' 	? ' <b>'.$lang->def('_START_TIME').' </b>'.$GLOBALS['regset']->databaseToRegional($start_time, 'date') 	: '' )
						.( $end_time != '' 		? ' <b>'.$lang->def('_END_TIME').' </b>'.$GLOBALS['regset']->databaseToRegional($end_time, 'date') 		: '' )
						.'<br />'
						, 'content');
				}
				$GLOBALS['page']->add( '<b>'.$lang->def('_ANALYSIS_DATE').' :</b> '.$date_now.'<br />'
				.'</div>', 'content');
				
				$group_user = $acl_man->getGroupAllUser($idst_group);
				
				// find some information
				$query_time ="
				SELECT idUser, idCourse, status, UNIX_TIMESTAMP(date_inscr), UNIX_TIMESTAMP(date_first_access), UNIX_TIMESTAMP(date_complete)
				FROM ".$GLOBALS['prefix_lms']."_courseuser 
				WHERE idUser IN (".implode(',', $group_user).")";
				if($start_time != '') $query_time .= " AND date_inscr >= '".$start_time."' ";
				if($end_time != '') $query_time .= " AND date_inscr <= '".$end_time."' ";
				
				$this->_printTable($acl_man, $query_time, $course, $users_info);
			}
		}
	}
	
	function _printTable(&$acl_man, $query_time, &$course, &$users_info) {
		
		$lang =& DoceboLanguage::createInstance('rd2_report');
		
		// Table
		$GLOBALS['page']->add(
			'<table class="report_table" summary="'.$lang->def('_RD2_SUMMAMRY_MANAGMENT').'">'
			.'<caption>'.$lang->def('_RD2_CAPTION').'</caption>'
			.'<thead>'
			.'<tr>'."\n\t"
				.'<th colspan="2">'.$lang->def('_TH_COURSE').'</th>'."\n\t"
				.'<th colspan="2">'.$lang->def('_TH_USER').'</th>'."\n"
				.'<th>'.$lang->def('_TH_TIMESTD').'</th>'."\n\t"
				.'<th>'.$lang->def('_TH_TIME_LATE').'</th>'."\n\t"
				.'<th rowspan="2" class="image">'.$lang->def('_TH_RISK_LEVEL').'</th>'."\n\t"
			.'</tr>'
			.'<tr>'."\n\t"
				.'<th>'.$lang->def('_TH_CODE_COURSE').'</th>'."\n\t"
				.'<th>'.$lang->def('_TH_NAME_COURSE').'</th>'."\n\t"
				.'<th>'.$lang->def('_TH_CODE_USER').'</th>'."\n\t"
				.'<th>'.$lang->def('_TH_NAME_USER').'</th>'."\n\t"
				.'<th class="image">'.$lang->def('_TH_NUM_WEEK').'</th>'."\n\t"
				.'<th class="image">'.$lang->def('_TH_NUM_WEEK').'</th>'."\n\t"
			.'</tr>'
			.'</thead>'."\n\n"
			.'<tbody>'
		, 'content');
		
		// find some information
		$i = 0;
		$divisor = 0;
		$avg_medium_time = $avg_effective_time = $avg_risk_lv = 0;
		$now = time();
		$re_time = mysql_query($query_time);
		while(list($id_user, $id_course, $user_status, $d_iscr, $d_first, $d_complete) = mysql_fetch_row($re_time)) {
			
			$medium_time = $course[$id_course]['mediumTime'];
			if($d_complete === NULL) {
				//not complete
				//late is difference between iscr and now
				$day_late = (int)(($now - $d_iscr) / 86400) - $medium_time;
				if($day_late < 0) $day_late = '';
			} else {
				//complete
				//late is difference between iscr and complete
				$day_late = (int)(($d_complete - $d_iscr) / 86400) - $medium_time;
			}
			$avg_medium_time += $medium_time ; 
			if($day_late != '') {
				$avg_effective_time += $day_late;
				$divisor++;
			}
			$row = '<tr class="row'.( ++$i%2 ? '' : '-col' ).'">'."\n"
				.'<td>'.$course[$id_course]['code'].'</td>'."\n\t"
				.'<td>'.$course[$id_course]['name'].'</td>'."\n\t"
				.'<td>'.$acl_man->relativeId($users_info[$id_user][ACL_INFO_USERID]).'</td>'."\n\t"
				.'<td>'.$users_info[$id_user][ACL_INFO_FIRSTNAME].' '.$users_info[$id_user][ACL_INFO_LASTNAME].'</td>'."\n\t"
				.'<td class="image">'.number_format( ($medium_time / 7), 2, '.', '').' ('.$medium_time.' gg)'.'</td>'."\n\t"
				.'<td class="image">'.($day_late != '' 
					? number_format( ($day_late / 7), 2, '.', '').' ('.$day_late.' gg)' 
					: '' )
				.'</td>'."\n\t"
				.'<td class="image">';
			//risk level
			if( $day_late < 30 ) {
				$row .= 1;
				$avg_risk_lv += 1;
			}
			elseif( $day_late < 60 ) {
				$row .= 2;
				$avg_risk_lv += 2;
			}
			else {
				$row .= 3;
				$avg_risk_lv += 3;
			}
			$row .= '</td>'."\n\t";
			$row .= '</tr>'."\n";
				
			$GLOBALS['page']->add( $row, 'content');
		}
		$GLOBALS['page']->add('<tr class="total">'."\n\t"
				.'<td colspan="4">'.$lang->def('_AVERANGE').'</td>'."\n\t"
				.'<td class="image">'.($i ? number_format( ($avg_medium_time / (7 * $i) ), 2, '.', '') : '&nbsp;' ).'</td>'
				.'<td class="image">'.($divisor ? number_format( ($avg_effective_time / (7 * $divisor) ), 2, '.', '') : '&nbsp;' ).'</td>'
				.'<td class="image">'.($i ? number_format( ($avg_risk_lv / $i ), 2, '.', '') : '&nbsp;' ).'</td>'
			.'</tr>'
			.'</thead>'."\n\n"
			.'<tbody>'
		, 'content');
		
		$GLOBALS['page']->add( 
			'</tbody>'
			.'</table>', 'content');
	}
	
	function exportAsCvs($org_chart_subdivision, $start_time, $end_time) {
		
		$lang =& DoceboLanguage::createInstance('rd2_report');
		
		ob_end_clean();
		//content type forcing dowlad
		header("Content-type: application/download\n");
		//cache control
		header("Cache-control: private");
		//sending creation time
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		//content type
		header('Content-Disposition: attachment; filename="report_delay2 '.gmdate('d-m-Y H i s').'.csv"');
		
		require_once($GLOBALS['where_framework'].'/class.module/class.directory.php');
		require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
		
		$lang =& DoceboLanguage::createInstance('rd2_report');
		
		$acl_man 		= new DoceboACLManager();
		$course_man 	= new Man_Course();
		
		$elem_selected = unserialize(urldecode($_POST['elem_selected']));
		$user_selected = unserialize(urldecode($_POST['user_selected']));
		
		if(empty($user_selected)) exit();
		$users_info =& $acl_man->getUsers($user_selected);
		
		if($org_chart_subdivision == 1) {
			
			require_once($GLOBALS['where_framework'].'/lib/lib.orgchart.php');
			$org_man 	= new OrgChartManager();
			$org_name = $org_man->getFolderFormIdst($elem_selected);
		}
		
		// Retrive all the course
		$course =& $course_man->getAllCoursesWithMoreInfo();
		if(empty($course)) exit;
		
		if($org_chart_subdivision === 0) {
			
			// find some information
			$query_time = "
			SELECT idUser, idCourse, status, UNIX_TIMESTAMP(date_inscr), UNIX_TIMESTAMP(date_first_access), UNIX_TIMESTAMP(date_complete)
			FROM ".$GLOBALS['prefix_lms']."_courseuser 
			WHERE idUser IN (".implode(',', $user_selected).")";
			if($start_time != '') $query_time .= " AND date_inscr >= '".$start_time."' ";
			if($end_time != '') $query_time .= " AND date_inscr <= '".$end_time."' ";
			
			$this->_printCsvTable($acl_man, $query_time, $course, $users_info);
		} else {
			
			$date_now = $GLOBALS['regset']->databaseToRegional(date("Y-m-d H:i:s")); 
			
			reset($org_name);
			while(list($idst_group, $folder_name) = each($org_name)) {
				
				echo "\r\n"
					.''.$lang->def('_FOLDER_NAME').' : '.$folder_name['name']
						.( $folder_name['type_of_folder'] == ORG_CHART_WITH_DESCENDANTS ? ' ('.$lang->def('_WITH_DESCENDANTS').')' : '' )."\r\n";
				if($start_time != '' || $end_time != '') {
					
					echo ''.$lang->def('_TIME_BELT_2').' : '
						.( $start_time != '' 	? ' '.$lang->def('_START_TIME').' '.$GLOBALS['regset']->databaseToRegional($start_time, 'date') 	: '' )
						.( $end_time != '' 		? ' '.$lang->def('_END_TIME').' '.$GLOBALS['regset']->databaseToRegional($end_time, 'date') 		: '' )
						."\r\n";
				}
				echo ''.$lang->def('_ANALYSIS_DATE').' : '.$date_now."\r\n";
				
				$group_user = $acl_man->getGroupAllUser($idst_group);
				
				// find some information
				$query_time ="
				SELECT idUser, idCourse, status, UNIX_TIMESTAMP(date_inscr), UNIX_TIMESTAMP(date_first_access), UNIX_TIMESTAMP(date_complete)
				FROM ".$GLOBALS['prefix_lms']."_courseuser 
				WHERE idUser IN (".implode(',', $group_user).")";
				if($start_time != '') $query_time .= " AND date_inscr >= '".$start_time."' ";
				if($end_time != '') $query_time .= " AND date_inscr <= '".$end_time."' ";
				
				$this->_printCsvTable($acl_man, $query_time, $course, $users_info);
			}
		}
		
		exit();
	}
	
	function _printCsvTable(&$acl_man, $query_time, &$course, &$users_info) {
		
		$lang =& DoceboLanguage::createInstance('rd2_report');
		
		// Table
		echo $lang->def('_RD2_CAPTION')."\n\n";
		
		echo strip_tags($lang->def('_TH_COURSE').';;'
				.$lang->def('_TH_USER').';;'
				.$lang->def('_TH_TIMESTD').';'
				.$lang->def('_TH_TIME_LATE').';'
				.$lang->def('_TH_RISK_LEVEL')
			."\n"
				.$lang->def('_TH_CODE_COURSE').';'
				.$lang->def('_TH_NAME_COURSE').';'
				.$lang->def('_TH_CODE_USER').';'
				.$lang->def('_TH_NAME_USER').';'
				.$lang->def('_TH_NUM_WEEK').';'
				.$lang->def('_TH_NUM_WEEK').';'
			."\n");
		
		// find some information
		$i = 0;
		$divisor = 0;
		$avg_medium_time = $avg_effective_time = $avg_risk_lv = 0;
		$now = time();
		$re_time = mysql_query($query_time);
		while(list($id_user, $id_course, $user_status, $d_iscr, $d_first, $d_complete) = mysql_fetch_row($re_time)) {
			
			$medium_time = $course[$id_course]['mediumTime'];
			if($d_complete === NULL) {
				//not complete
				//late is difference between iscr and now
				$day_late = (int)(($now - $d_iscr) / 86400) - $medium_time;
			if($day_late < 0) $day_late = '';
			} else {
				//complete
				//late is difference between iscr and complete
				$day_late = (int)(($d_complete - $d_iscr) / 86400) - $medium_time;
			}
			$avg_medium_time += $medium_time ; 
			if($day_late != '') {
				$avg_effective_time += $day_late;
				$divisor++;
			}
			
			$row = ereg_replace(';', '', $course[$id_course]['code']).';'
				.ereg_replace(';', '', $course[$id_course]['name']).';'
				.ereg_replace(';', '', $acl_man->relativeId($users_info[$id_user][ACL_INFO_USERID])).';'
				.ereg_replace(';', '', $users_info[$id_user][ACL_INFO_FIRSTNAME].' '.$users_info[$id_user][ACL_INFO_LASTNAME]).';'
				.number_format( ($medium_time / 7), 2, '.', '').' ('.$medium_time.' gg)'.';'
				.($day_late != '' 
					? number_format( ($day_late / 7), 2, '.', '').' ('.$day_late.' gg)' 
					: '' ).';';
			//risk level
			if( $day_late < 30 ) {
				$row .= 1;
				$avg_risk_lv += 1;
			}
			elseif( $day_late < 60 ) {
				$row .= 2;
				$avg_risk_lv += 2;
			}
			else {
				$row .= 3;
				$avg_risk_lv += 3;
			}
			echo $row."\n";
			$i++;
		}
		echo $lang->def('_AVERANGE').';;;'
				.($i ? number_format( ($avg_medium_time / (7 * $i) ), 2, '.', '') : '' ).';'
				.($divisor ? number_format( ($avg_effective_time / (7 * $divisor) ), 2, '.', '') : '' ).';'
				.($i ? number_format( ($avg_risk_lv / $i ), 2, '.', '') : '' );
		
		
	}
}

?>