<?php
setlocale(LC_ALL, 'sv_SE');
setlocale(LC_ALL, "sv_SE");
setlocale(LC_TIME, 'sv_SE');
setlocale(LC_TIME, "sv_SE");
date_default_timezone_set('Europe/Stockholm');
date_default_timezone_set("Europe/Stockholm");
/*
  CourseMS
  https://sourceforge.net/projects/coursems

  Copyright (c) 2007 Jacques Malan

  This version of the code is released under the GNU General Public License
*/
	// page to display schedule
	$access_level = '3';
	$access_error = false;
	$require_error = false;
	
	include('includes/application_top.php');
	
	$course_id_request = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : '';
	$course_id_get     = isset($_GET['course_id'])     ? $_GET['course_id'] : '';
	$center_request    = isset($_REQUEST['center'])    ? $_REQUEST['center'] : '';
	$center_post       = isset($_POST['center'])       ? $_POST['center'] : '';
	$center_get        = isset($_GET['center'])        ? $_GET['center'] : '';
	$type_request      = isset($_REQUEST['type'])      ? $_REQUEST['type']   : '';
	$type_post         = isset($_POST['type'])         ? $_POST['type']   : '';
	$type_get          = isset($_GET['type'])          ? $_GET['type']   : '';
	$category_request  = isset($_REQUEST['category'])  ? $_REQUEST['category']   : '';
	$category_post     = isset($_POST['category'])     ? $_POST['category']   : '';
	$category_get      = isset($_GET['category'])      ? $_GET['category']   : '';
	$action_request    = isset($_REQUEST['action'])    ? $_REQUEST['action'] : '';
	$action_post       = isset($_POST['action'])       ? $_POST['action'] : '';
	$action_get        = isset($_GET['action'])        ? $_GET['action'] : '';
	$month_post        = isset($_POST['month'])        ? $_POST['month'] : '';
	$month_get         = isset($_GET['month'])         ? $_GET['month'] : '';
	$id_request        = isset($_REQUEST['id'])        ? $_REQUEST['id'] : '';	
	$id_post           = isset($_POST['id'])           ? $_POST['id'] : '';
	$id_get            = isset($_GET['id'])            ? $_GET['id'] : '';
	$center = ''; $type = ''; $category = ''; $course_id = '';
	
	if (!isset($_SESSION['learner'])) {
		header("Location: login.php");
	}
	if(time() - $_SESSION['timestamp'] > Session_time_out) { //subtract new timestamp from the old one
		echo"<script>alert('Du har automatiskt loggats ut p.g.a för lång inaktivitet.');</script>";
		unset($_SESSION['learner'], $_SESSION['timestamp']);
		$_SESSION['logged_in'] = false;
		header("Location: login.php"); //redirect to index.php
		exit;
	} 
	else {
		$_SESSION['timestamp'] = time(); //set new timestamp
	}
	
	
	$user = $_SESSION['learner'];
		$user->set_profile();

	$course_start_date = false;
	$min_date = false;
//echo 'Tjingeling från 16 center:' ,$center, ' getmonth:' ,$getmonth, ' getmonth2:' ,$getmonth2, ' getmonth3:' ,$getmonth3, ' action:' ,$action, ' type:' ,$type, ' category:' ,$category, ' course_id:' ,$course_id,'<br>';
	if (strlen($course_id_request) > 0) {
		$course_id = $course_id_request;
		// lets find first date of this course and jump the calendar to this date
		$t_date = date('Y-m-d');
		$query = "select min(start_date)'min_date', max(start_date)'max_date' from " .
				"calendar " .
				"where " .
				"course_id = '$course_id' and start_date > '$t_date'";
		$result = tep_db_query($query);
		if (tep_db_num_rows($result) > 0) {
			$row = tep_db_fetch_array($result);
			if (!isset($_REQUEST['month'])) {
				$course_start_date = $row['min_date'];
				$last_course_date = $row['max_date'];
			}
			$min_date = $row['min_date'];
			$max_date = $row['max_date'];
//echo 'max_date: ',$max_date,' AAA ', substr($max_date,5,2)+1,' BBB ',substr($max_date,9,2),' CCC ',substr($max_date,0,4);
			$max_date = date('Y-m-d', mktime(0,0,0, substr($max_date,5,2)+1, substr($max_date,9,2), substr($max_date,0,4)));
		}
	}
	if (isset($_GET['action'])) {
//echo 'Tjingeling från 5';
		if ($action_get == 'register') {
			$user_id = $id_get;
			$user = new user(tep_get_username($user_id));
			$user->set_profile();
		}
	}
	// filter
	$where_array = array();
	if (isset($_POST['filter'])) {
		$center = $center_post;
		$type = $type_post;
		$category = $category_post;
		$course = isset($_POST['course'])?$_POST['course']:'';
		$day = isset($_POST['day'])?$_POST['day']:'';
		$month = $month_post;
		if (strlen($month) == 1)
			$month = '0'.$month;
		$year = $_POST['year'];
		$range = tep_get_month_range($month, $year);
		$start_date = $year.'-'.$month.'-01';
		$end_date = $year.'-'.$month.'-'.$range;
	}
	else if (isset($_GET['month']))
	{
//echo 'Tjingeling från 17 center:' ,$center, ' getmonth:' ,$getmonth, ' getmonth2:' ,$getmonth2, ' getmonth3:' ,$getmonth3, ' action:' ,$action, ' type:' ,$type, ' category:' ,$category, ' course_id:' ,$course_id,'<br>';
		$start_date = $_GET['start_date'];
		$year = substr($start_date,0,4);
		$month = substr($start_date,5,2);
		$day = '';
		if ($month_get == 'previous') {
//echo 'Tjingeling från 2';
			$start_date = date('Y-m-d', mktime(0,0,0,$month-1,1,$year));
		}
		else if ($month_get == 'next') {
//echo 'Tjingeling från 3';
			$start_date = date('Y-m-d', mktime(0,0,0,$month+1,1,$year));
		}
		$month = substr($start_date,5,2);
		$year = substr($start_date,0,4);
		$range = tep_get_month_range($month, $year);
		$end_date = date('Y-m-d', mktime(0,0,0,$month, $range, $year));
		$center = $center_get;
		$category = $category_get;
		$type = $type_get;
	}
	else
	{
		$range = tep_get_month_range(date('m'),date('Y'));
		$day = date('d');
		$month = date('m');
		$year = date('Y');
		$start_date = date('Y').'-'.date('m').'-01';
		$end_year = date('Y');
		$end_date = $end_year.'-'.date('m').'-'.$range;
	}
	// building the where clause for the SQL to filter out results
	if ($course_start_date) {
		$start_date = substr($course_start_date,0,4).'-'.substr($course_start_date,5,2).'-01';
		$month = substr($start_date,5,2);
		$year = substr($start_date,0,4);
		$range = tep_get_month_range($month, $year);
		$end_date = date('Y-m-d', mktime(0,0,0,$month, $range, $year));
	}
	if ($center >= 1) {
		$where_array['center'] = $center;
	}
	if ($type >= 1) {
		$where_array['type'] = $type;
	}
	if ($category >= 1) {
		$where_array['category'] = $category;
	}
	if ($course_id >= 1) {
		$where_array['id'] = $course_id;
	}
	$counter = 0;
	foreach ($where_array as $a=>$b) {
		if ($counter == 0) {
			$where_clause = 'c.'.$a.' = '.$b;
		}
		else
		{
			$where_clause .= ' and c.'.$a.' = '.$b;
		}
		$counter++;
	}
	if(!isset($where_clause))
		$where_clause = '';
	//filter to show courses only valid for this users job title
	If (JOB_REQUIREMENTS=='true') {
		If (strlen($where_clause)>0) $where_clause .= " and ";
		 $where_clause .= "  requirement_type='job' and requirement_id=".$user->job_title_id;
	}
	// end where clause
	$action = $action_get;
	switch ($action) {
		case 'delete':  if (tep_validate_user($_SESSION['admin_user'], $access_level, tep_get_course_center($course_id_get))) {
					tep_delete_entry(TABLE_CALENDAR, $id_get);
					// TODO:
					// need to remove registrations for this course
					// this option has been removed from the UI
				}
				else
				{
					$access_error = true;
					$error = PERMISSION_ERROR;
				}
				break;
		case 'cancel': if (tep_validate_user($_SESSION['admin_user'], $access_level, tep_get_course_center($course_id_get))) {
					tep_cancel_course($id_get);
				}
				else
				{
					$access_error = true;
					$error = PERMISSION_ERROR;
				}
				break;
		case 'reschedule': if (tep_validate_user($_SESSION['admin_user'], $access_level, tep_get_course_center($course_id_get))) {
					tep_reschedule_course($id_get);
				}
				else
				{
					$access_error = true;
					$error = PERMISSION_ERROR;
				}
				break;
		case 'move': if (tep_validate_user($_SESSION['admin_user'], $access_level, tep_get_course_center($course_id))) {
					$o_cal_id = $_GET['o_cal_id'];
				}
				else
				{
					$access_error = true;
					$error = PERMISSION_ERROR;
				}
				break;
	}
	$schedule_array = array();
	if (strlen($where_clause)>0) {
		$query = "select ca.id, " .
				"ca.course_id, " .
				"ca.start_date, " .
				"ca.start_time, " .
				"ca.end_time, " .
				"ca.dates, " .
				"ca.resources, " .
				"ca.cancelled, " .
				"ca.registered, ".
				"c.center, " .
				"c.type, " .
				"c.name, " .
				"c.max_attendance ".
				"from calendar as ca " .
				"left join " .
				"courses as c " .
				"on (ca.course_id = c.id) " .
				"left join requirements on c.id=requirements.course_id " . 
				"where ".$where_clause." " .
				"order by " .
				"ca.start_date, " .
				"c.center, " .
				"c.type, " .
				"ca.start_time, " .
				"c.name";
	}
	else
	{
		$query = "select ca.id, " .
				"ca.course_id, " .
				"ca.start_date, " .
				"ca.start_time, " .
				"ca.end_time, " .
				"ca.dates, " .
				"ca.resources, " .
				"ca.cancelled, " .
				"ca.registered, ".
				"c.center, " .
				"c.type, " .
				"c.name, " .
				"c.max_attendance ".
				"from calendar as ca " .
				"left join " .
				"courses as c on (ca.course_id = c.id) " .
				"order by " .
				"ca.start_date, " .
				"c.center, " .
				"c.type, " .
				"ca.start_time, " .
				"c.name";
	}
	$result = tep_db_query($query);
	while ($row = tep_db_fetch_array($result)) {
		foreach (unserialize($row['dates']) as $a=>$date) {
			if ($min_date) {
				//if ($date >= $min_date && $date <= $max_date) {
					$schedule_array[] = array(	'date' => $date,
												'course_id' => $row['course_id'],
												'id' => $row['id'],
												'max' => $row['max_attendance'],
												'reg' => $row['registered']);
				//}
			}
			else
			{
				//if ($date >= $start_date && $date <= $end_date) {
					$schedule_array[] = array(	'date' => $date,
												'course_id' => $row['course_id'],
												'id' => $row['id'],
												'max' => $row['max_attendance'],
												'reg' => $row['registered']);
				//}
			}
		}
	}
	$course_start_date = $row['min_date'];
			$last_course_date = $row['max_date'];
	function cmp($a, $b) {
		return strnatcasecmp( $a['date'], $b['date'] );
	}
	usort($schedule_array, "cmp");
	// template for page build
	include(INCLUDES . 'header.php');
	include(INCLUDES . 'front_header.php');
?>
	<TABLE width="100%" cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#ffffff">
		<tr>
			<td colspan=3><IMG height=10 src="images/blank.gif" width=1></td>
		</tr>
		<tr>
			<td width="3%" rowspan=2><IMG height=45 src="images/line.gif" width=24></td>
			<td class="title" height="27" colspan=3>&nbsp;Schema</td>
		</tr>
		<tr>
			<td width="2%"><IMG src="images/left.gif"></td>
			<?php
			if (strlen($action_get) > 0) {
				if ($action_get == 'register') { ?>
					<td height="18" class="subtitle" valign="bottom" width="20%">Välj kurstillfälle som du vill anmäla <?php echo $user->firstname.' '.$user->lastname; ?> till.</td>
				<?php
				}
			}
			else
			{
				?><td height="18" class="subtitle" valign="bottom" width="20%">Visar schema</td><?php
			}
			?>
			<td width="83%"><IMG src="images/right.gif"></td>
		</tr>
	</TABLE>
	
	<TABLE width="100%" cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#ffffff">
		<tr>
			<td align="middle">
				<!-- main content starts here -->
				<table width="960px" align="center" cellspacing="1" cellpadding="3">
					<tr>
						<td>
							<table width='100%'>
								<!-- CONTENT -->
								<?php
								if ($access_error) {
								?>
									<tr>
										<td>
											<?php echo $error; ?>
										</td>
									</tr>
								<?php
								}
								?>
								<tr>
									<td>
										<table width="100%">
<!--											<tr>
												<?php
												if (isset($_GET['action'])) {
													?><form name="filter" action="view_schedule.php?action=<?php echo $action_get; ?>&course_id=<?php echo $course_id_get; ?>&id=<?php echo $id_get; ?>" method="post"><?php
												}
												else
												{
												?>
													<form name="filter" action="view_schedule.php" method="post">
												<?php
												}
												?>
												
												<td class="left">Plats:   </td><td class="right"><?php echo tep_build_dropdown(TABLE_CENTERS, 'center', false, 1, '', true, $center_request); ?></td>
												<td class="left">Typ:     </td><td class="right"><?php echo tep_build_dropdown(TABLE_COURSE_TYPES, 'type', false, 1, '', true, $type_request); ?></td>
												<td class="left">Kategori:</td><td class="right"><?php echo tep_build_dropdown(TABLE_COURSE_CATEGORIES, 'category', false, 1, '', true, $category_request); ?></td>
												<td class="left">Kurs:    </td><td class="right"><?php echo tep_build_dropdown(TABLE_COURSES, 'course_id', false, 1, '', true, $course_id_request); ?></td>
											</tr>
											<tr>
												<?php if(!isset($day)){$day = '';} ?>
												<td class="left">År:</td><td class="right"><?php echo tep_build_date_dropdown('year','year', $year, $month, $day, 8,5); //build_date_dropdown(menu_name, type: year/month/day, selected_date, lead_in, lead_out)
												?></td>
												<td class="left">Månad:</td><td class="right"><?php echo tep_build_date_dropdown('month','month', $year, $month, $day); //no lead in or lead out options
												?></td>
												<td class="left">&nbsp;</td>
												<td class="right">&nbsp;</td>
												<td class="left"><a href="view_schedule.php">Reset</a></td>
												<td class="left"><input type="submit" name="filter" class="submit3" value="Filter"></td>
												</form>
											</tr>
										</table>
-->									</td>
								</tr>
								<tr>
									<td align="left">
										<h4>Visar schemaperiod:&nbsp;&nbsp;<?php echo $start_date; ?>&nbsp;to&nbsp;<?php echo $end_date;?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
										<a href="view_schedule.php?month=previous&start_date=<?php echo $start_date; ?>&center=<?php echo $center; ?>&category=<?php echo $category; ?>&type=<?php echo $type; ?>&action=<?php echo $action_get; ?>&id=<?php echo $id_get ?>&course_id=<?php echo $course_id_request; ?>"> < Föregående</a>&nbsp;|&nbsp;<a href="view_schedule.php?month=next&start_date=<?php echo $start_date; ?>&center=<?php echo $center; ?>&category=<?php echo $category; ?>&type=<?php echo $type; ?>&action=<?php echo $action; ?>&id=<?php echo $id_get ?>&course_id=<?php echo $course_id_request; ?>">Nästa ></a></h4>
									</td>
								</tr>
								<?php
								if (isset($_GET['action'])) {
									if ($action_get == 'register') {
										?>
										<tr>
											<td class="hright"><font size="2px">Välj kurstillfälle som du vill anmäla dig till. Klicka <a href="view_schedule.php">här</a> för att återgå till översikt av schema.</font></td>
										</tr>
										<?php
									}
								}
								if (count($schedule_array) == 0) { ?>
									<tr>
										<td class="right">
											Det finns inga schemalagda kurser tillgängliga för anmälan.
										</td>
									</tr>
								<?php
								}
								?>
					<tr>
						<td colspan=3 align=right></td>
					</tr>
				</table>
			</tr>
		</td>
		</table>
		<table width="90%" align="center">
			<tr>
				<td><?php echo tep_schedule_calendar(substr($start_date,0,4), substr($start_date,5,2), $schedule_array); 
				?></td>
			</tr>
		</table>
		<?php
		// add other instances of a course if action = register or course_id is set
		if (strlen($course_id_request) > 0) {
		?>
			<table width="90%" align="center">
				<tr>
					<td class="hright" colspan="5"><span class="head">Alla kommande datum för: <?php echo tep_get_name(TABLE_COURSES, $course_id_request); ?></span></td>
				</tr>
				<tr>
					<td class="hcenter" width="4%"><span class="head">ID</span></td>
					<td class="hleft" width="25%"><span class="head">Startdatum:</span></td>
					<td class="hleft" width="25%"><span class="head">Kursnamn</span></td>
					<td class="hleft" width="25%" colspan="2"><span class="head">Åtgärd</span></td>
				</tr>
				<?php
				$temp_id = 0;
				if (count($schedule_array) == 0) {
					?>
					<tr>
						<td class="right" colspan="5">Det finns inga schemalagda tillfällen.</td>
					</tr>
					<?php
				}
				else
				{
					foreach ($schedule_array as $a => $b) {
						if ($b['date'] > date('Y-m-d') && $b['id'] != $temp_id) {

							$temp_id = $b['id'];
							?>
							<tr>
								<td class="left"><?php echo $b['id']; ?></td>
								<td class="left"><?php echo $b['date']; ?></td>
								<td class="left"><?php echo tep_get_name(TABLE_COURSES, $b['course_id']); ?></td>
								<td class="left"><a href="course_register.php?id=<?php echo $b['id']; ?>&user_id=<?php echo $user->id; ?>">Anmäl dig</a></td>
								<td class="left"><a href="course_registrations.php?id=<?php echo $b['id']; ?>">Visa info om kursen</a></td>
							</tr>
							<?php
						}
					}
				}
				?>
			</table>
		<?php
		}
		?>
	</td>
</tr>
</TABLE>
<?php
	include(INCLUDES . 'rightmenu.php');
	include(INCLUDES . 'footer.php');
?>
