<?php

function get_category_name($categoryID)
{
	$tbl_courses_nodes = Database::get_main_table(TABLE_MAIN_CATEGORY);

	$sql = "SELECT name FROM {$tbl_courses_nodes} WHERE code='{$categoryID}'"; 
	$result = api_sql_query($sql, __FILE__, __LINE__);
	if (mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		$categoryName = $row['name'];
	}
	
	return $categoryName;
}

/**
 * counts the number of courses in a given course category
 * @author Zhong <poopsoft@163.com>
 * @return 
*/
function count_courses_in_category($categoryID)
{
	$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
	$sql = "SELECT count(*) FROM $tbl_course WHERE category_code" . (empty($categoryID) ? " IS NULL" : "='" . $categoryID . "'");
	$sql_result = api_sql_query($sql, __FILE__, __LINE__);
	$row = mysql_fetch_array($sql_result, MYSQL_NUM);
	
	return $row[0];
}

/**
 * displays the browsing of the course categories (faculties)
 * @author Zhong <poopsoft@163.com>
 * @return HTML code containing a list with all the categories and subcategories and the navigation to go one category up(if needed)
*/
function display_course_categories($categoryID, $up)
{
	$tbl_courses_nodes = Database::get_main_table(TABLE_MAIN_CATEGORY);

	$sql = "SELECT * FROM $tbl_courses_nodes WHERE parent_id " . (empty($categoryID) ? "IS NULL" : "='{$categoryID}'") . " GROUP BY code, parent_id  ORDER BY tree_pos ASC";
	$result = api_sql_query($sql, __FILE__, __LINE__);

	$html = "";
	if (mysql_numrows($result) > 0)
	{
		$html = "<ul>\n";
		while ($row=mysql_fetch_array($result))
		{
			$course_count = count_courses_in_category($row['code']);
			if ($row['children_count'] > 0 || $course_count > 0)
			{
				$html .= "<li><a href='{$_SERVER['PHP_SELF']}?action=subscribe&amp;category={$row['code']}&amp;up={$categoryID}'>{$row['name']}</a>({$course_count})</li>\n";
			}
			else
			{
				$html .= "<li>{$row['name']}</li>\n";
			}
		}
		$html .= "</ul>\n";
	}
	else 
	{
		$html .= "<span style='margin-left:30px;'>" . get_lang('NoSubCategory') . "</span><br><br>\n";
	}
	
	if ($_GET['category'])
	{
		$html .= "<a href='{$_SERVER['PHP_SELF']}?action=subscribe&amp;category={$up}'>&laquo; " . get_lang('UpOneCategory') . "</a>\n";
		$html .= "<br><br>\n";
	}

	$html .= display_search_courses_form($categoryID, $up);
	
	return $html;
}

/**
 * displays the form for searching for a course and the results if a query has been submitted.
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @return HTML code: the form for searching for a course
*/
function display_search_courses_form($categoryID, $up)
{
	global $_user;
	$html = "<form style='margin-bottom:10px;' method='post' action='{$_SERVER['PHP_SELF']}?action=subscribe&category={$categoryID}&up={$up}'>\n";
	$html .= "<input type='text' name='search_term' size='15' value='{$_REQUEST['search_term']}' />&nbsp;\n";
	$html .= "<input type='submit' class='inputSubmit' value='" . get_lang("_search") . "' />\n";
	$html .= "</form>\n";

	return $html;
}

/**
 * Display all the courses in the given course category. 
 * @author Zhong <poopsoft@163.com>
 * @return HTML code: a table with all the courses in a given category (title, code, tutor) and a subscription icon if applicable)
*/
function display_courses_in_category($categoryID, $start, $searchTerm)
{
	if (!isset($start))
	{
		$start = '0';
	}
	
	//courses[0] is course total	courses[1] is course list
	$courses = array();

	if (! empty($_REQUEST['search_term']))
	{
		$courses = search_courses($categoryID, $start, $searchTerm);
	}
	else 
	{
		$courses = get_courses_in_category($categoryID, $start);
	}
	
	if ($courses[0] > 0)
	{
		$html = display_subscribe_to_courses($categoryID, $start, $searchTerm, $courses[1], $courses[0]);
	}
	
	return $html;
}

/**
 * Search the courses database for a course that matches the search term.
 * The search is done on the code, title and tutor field of the course table.
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $search_term: the string that the user submitted, what we are looking for
 * @param string $category: the current category that the user are browsering
 * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... )
 * 			matching the the search term.
*/
function search_courses($categoryID, $start, $searchTerm)
{
	$TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);

	$sql_find = "FROM {$TABLECOURS} WHERE (code LIKE '%{$searchTerm}%' OR title LIKE '%{$searchTerm}%' OR tutor_name LIKE '%{$searchTerm}%')";
	if (! empty($categoryID))
	{
		$sql_find .= " and category_code='{$categoryID}'";
	}
	
	$sql = "SELECT count(*) " . $sql_find;
	$result_find_count = api_sql_query($sql, __FILE__, __LINE__);
	$row = mysql_fetch_array($result_find_count, MYSQL_NUM);
	$courses[] = $row[0];
	
	$sql = "SELECT * " . $sql_find . " LIMIT " . ($start * NUMBER_PAGE) . "," . NUMBER_PAGE;
	$result_find = api_sql_query($sql, __FILE__, __LINE__);
	while ($row = mysql_fetch_array($result_find, MYSQL_ASSOC))
	{
		$course[]=array("code" => $row['code'], "directory" => $row['directory'], "db"=> $row['db_name'], "visual_code" => $row['visual_code'], "title" => $row['title'], "tutor" => $row['tutor_name'], "subscribe" => $row['subscribe'], "unsubscribe" => $row['unsubscribe'], 'registration_code'=> $row['registration_code'], "visibility" => $row['visibility']);
	}
	$courses[] = $course;
	
	return $courses;
}

/**
 * Get all the courses in the current browser course category. 
 * @author Zhong <poopsoft@163.com>
 * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... )
 * 			matching the the category.
*/
function get_courses_in_category($categoryID, $start)
{
	$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
	$sql_find = "FROM {$tbl_course} WHERE category_code " . (empty($categoryID) ? " IS NULL" : "='" . $categoryID . "'");

	$sql = "SELECT count(*) " . $sql_find;
	$result_find_count = api_sql_query($sql, __FILE__, __LINE__);
	$row = mysql_fetch_array($result_find_count, MYSQL_NUM);
	$courses[] = $row[0];
	
	$sql = "SELECT * " . $sql_find . " LIMIT " . ($start * NUMBER_PAGE) . "," . NUMBER_PAGE;
	$result = api_sql_query($sql,__FILE__,__LINE__);
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
		if ($row['registration_code']=='')
		{
			$registration_code=false;
		}
		else
		{
			$registration_code=true;
		}
		$course[]=array("code" => $row['code'], "directory" => $row['directory'], "db"=> $row['db_name'], "visual_code" => $row['visual_code'], "title" => $row['title'], "tutor" => $row['tutor_name'], "subscribe" => $row['subscribe'], "unsubscribe" => $row['unsubscribe'], 'registration_code'=> $row['registration_code'], "visibility" => $row['visibility']);
	}
	$courses[] = $course;
	
	return $courses;
}

/**
 * This function displays the list of course that can be subscribed to.
 * This list can come from the search results or from the browsing of the platform course categories
*/
function display_subscribe_to_courses($categoryID, $start, $searchTerm, $courses, $total)
{
	global $_user;

	// getting all the courses to which the user is subscribed to
	$user_courses = get_courses_of_user($_user['user_id']);
	$user_coursecodes=array();
	// we need only the course codes as these will be used to match against the courses of the category
	if ($user_courses <> '')
	{
		foreach ($user_courses as $key=>$value)
		{
			$user_coursecodes[]=$value['code'];
		}
	}

	$html = "<div class='homeCourse'>\n";
	$html .= "<table border=0 class='contentData' cellspacing='0'>\n";
	$html .= "<tr>\n";
	$html .= "<th align='left'>" . Display::return_icon("star.gif") . "&nbsp;" . get_lang("CourseList") . "</th>\n";
	$html .= "</tr>\n";
	$html .= "<tr>\n";	
	$html .= "<td align='center' valign='top'>\n";
	
	$html .= "<table border=0 width='100%' cellpadding='0' cellspacing='0'>\n";
	$counter = 0;
	foreach ($courses as $key=>$course)
	{
		if (($counter % 2) == 0) {
			$oddclass = "row_odd";
		} else {
			$oddclass = "row_even";
		}
		// displaying the course title, visual code and teacher/teaching staff
		$html .= "<tr class='{$oddclass}'>\n";
		$html .= "<td width='85%' align='left'>\n";

		if (! isset($_user['user_id'])) {
			if ($course['visibility'] == 3) {
				$html .= "<a href='" . api_get_path(WEB_COURSE_PATH) . "{$course['directory']}'>{$course['title']}</a><br>";
			} else {
				$html .= "<b>{$course['title']}</b><br />";
			}
		} else {
			if ($course['visibility'] >= 2) {
				$html .= "<a href='" . api_get_path(WEB_COURSE_PATH) . "{$course['directory']}'>{$course['title']}</a><br>";
			} else {
				$html .= "<b>{$course['title']}</b><br />";
			}			
		}
		
		if (get_setting("display_coursecode_in_courselist") == "true")
		{
			$html .= $course['visual_code'];
		}
		if (get_setting("display_coursecode_in_courselist") == "true" && get_setting("display_teacher_in_courselist") == "true")
		{
			$html .= " - ";
		}
		if (get_setting("display_teacher_in_courselist") == "true")
		{
			$html .= $course['tutor'];
		}
		$html .= "</td>\n";

		$html .= "<td width='15%' align='left'>\n";
		$html .= display_subscribe_icon($course, $user_coursecodes);
		$html .= "</td>\n";

		$html .= "</tr>\n";
	}
	$html .= "</table>\n";

	if (($total % NUMBER_PAGE) == 0)
	{
		$pages = intval($total/NUMBER_PAGE);
	}
	else 
	{
		$pages = intval($total/NUMBER_PAGE) + 1;
	}
	$html .= "<div style='float:left;margin-top:5px;'>";
	$html .= ($start + 1) . " / " . $pages;
	$html .= "</div>";
	$html .= "<div style='float:right;margin-top:5px;'>";
	$next = $start + 1;
	$prev = $start - 1;
	if($start == 0)
	{
		$html .= Display::return_icon('prev.gif', get_lang('PreviousPage')) . "&nbsp;&nbsp;&nbsp;";
		if($total > NUMBER_PAGE)
		{
			$html .= "<a href='{$_SERVER['PHP_SELF']}?action=subscribe&category={$categoryID}&search_term=" . urlencode($searchTerm) . "&start={$next}'>";
			$html .=  Display::return_icon('next.gif', get_lang('NextPage')) . "</a>\n";
		}
		else 
		{
			$html .= Display::return_icon('next.gif', get_lang('NextPage'));
		}
	}
	else
	{
		$html .= "<a href='{$_SERVER['PHP_SELF']}?action=subscribe&category={$categoryID}&search_term=" . urlencode($searchTerm) . "&start={$prev}'>";
		$html .= Display::return_icon('prev.gif', get_lang('PreviousPage')) . "</a>&nbsp;&nbsp;&nbsp;";

		if($total-($start * NUMBER_PAGE) > NUMBER_PAGE)
		{
			$html .= "<a href='{$_SERVER['PHP_SELF']}?action=subscribe&category={$categoryID}&search_term=" . urlencode($searchTerm) . "&start={$next}'>";
			$html .= Display::return_icon('next.gif', get_lang('NextPage')) . "</a>\n";
		}
		else 
		{
			$html .= Display::return_icon('next.gif', get_lang('NextPage'));
		}
	}
	$html .= "</div>";

	$html .= "</td>\n";
	$html .= "</tr>\n";
	$html .= "</table>\n";
	$html .= "</div>\n";

	return $html;
}

/**
 * displays the subscribe icon if the subscribing is allowed and if the user is not yet
 * subscribe to this course
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $current_course: the course code of the course we need to display the subscribe icon for
 * @return string a subscribe icon or the text that subscribing is not allowed or the user is already subscribed
*/
function display_subscribe_icon($current_course, $user_coursecodes)
{

	// we display the icon to subscribe or the text already subscribed
	if (in_array($current_course['code'], $user_coursecodes))
	{
		$html = get_lang("AlreadySubscribed");
	}
	else
	{
		if ($current_course['subscribe'] == SUBSCRIBE_ALLOWED)
		{
			$html = "<form style='margin:0px;' action='{$_SERVER["REQUEST_URI"]}' method='post'>\n";
			$html .= "<input type='hidden' name='subscribe' value='{$current_course['code']}' />\n";
			$html .= "<input type='image' name='unsub' src='" . api_get_path(WEB_IMG_PATH) . "enroll.gif' title='" . get_lang("Subscribe") . "' />";
			$html .= "</form>\n";
		}
		else
		{
			if (!empty($current_course['registration_code']))
			{
				$html .= Display::return_icon('passwordprotected.png', get_lang("SubscribingNotAllowed"), array('style'=>'float:left;vertical-align:middle;'));
			}
			else 
			{
				$html .= get_lang("SubscribingNotAllowed");
			}
		}
	}
	
	return $html;
}

/**
 * retrieves all the courses that the user has already subscribed to
 * @author Zhong <poopsoft@163.com>
 * @param int $user_id: the id of the user
 * @return array an array containing all the information of the courses of the given user
*/
function get_courses_of_user($user_id)
{
	$TABLECOURS=Database::get_main_table(TABLE_MAIN_COURSE);
	$TABLECOURSUSER=Database::get_main_table(TABLE_MAIN_COURSE_USER);

	// Secondly we select the courses that are in a category (user_course_cat<>0) and sort these according to the sort of the category
	$user_id = intval($user_id);
	$sql_select_courses="SELECT course.code k, course.visual_code  vc, course.subscribe subscr, course.unsubscribe unsubscr,
								course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status,
								course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
		                        FROM    $TABLECOURS       course,
										$TABLECOURSUSER  course_rel_user
		                        WHERE course.code = course_rel_user.course_code
		                        AND   course_rel_user.user_id = '".$user_id."'
		                        ORDER BY course_rel_user.sort ASC";
	$result = api_sql_query($sql_select_courses,__FILE__,__LINE__) or die(mysql_error());
	while ($row=mysql_fetch_array($result))
	{
		// we only need the database name of the course
		$courses[]=array("db"=> $row['db'], "code" => $row['k'], "visual_code" => $row['vc'], "title" => $row['i'], "directory" => $row['dir'], "status" => $row['status'], "tutor" => $row['t'], "subscribe" => $row['subscr'], "unsubscribe" => $row['unsubscr'], "sort" => $row['sort'], "user_course_category" => $row['user_course_cat']);
		}

	return $courses;
}

?>