<?php
//index.php
include 'connect.php';
include 'header.php';

$sql = "SELECT categories.catNo, categories.catName, categories.catDescr, COUNT(topics.topicNo) AS topics
				FROM categories LEFT JOIN
					topics ON topics.topicNo = categories.catNo
				GROUP BY categories.catName, categories.catDescr, categories.catNo";

if(!$result = $conn->query($sql))
{
	echo 'The categories could not be displayed, please try again later.';
}
else
{
	if($result->num_rows == 0)
	{
		echo 'No categories defined yet.';
	}
	else
	{
		//prepare the table
		echo '<table border="1">
			  <tr>
				<th>Category</th>
				<th>Last topic</th>
			  </tr>';

		while($row = $result->fetch_assoc())
		{
			echo '<tr>';
				echo '<td class="leftpart">';
					echo '<h3><a href="category.php?id=' . htmlentities($row['catNo'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '">' . htmlentities($row['catName'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '</a></h3>' . htmlentities($row['catDescr'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
				echo '</td>';
				echo '<td class="rightpart">';

				//fetch last topic for each cat
					$topicsql = "SELECT	topicNo, topicSubject, topicDate, topicCat
											 FROM topics
											 WHERE topicCat = ?
											 ORDER BY topicDate DESC
											 LIMIT 1";

					$stmt = $conn->prepare($topicsql);
					$stmt->bind_param('i', $row['catNo']);
					$stmt->execute();

					if(!$topicsresult = $stmt->get_result())
					{
						echo 'Last topic could not be displayed.';
					}
					else
					{
						if($topicsresult->num_rows == 0)
						{
							echo 'no topics';
						}
						else
						{
							while($topicrow = $topicsresult->fetch_assoc())
							echo '<a href="topic.php?id=' . htmlentities($topicrow['topicNo'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '">' . htmlentities($topicrow['topicSubject'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '</a> on ' . htmlentities(date('d-m-Y', strtotime($topicrow['topicDate'])), ENT_QUOTES | ENT_HTML5, 'UTF-8');
						}
					}
				echo '</td>';
			echo '</tr>';
		}
	echo '</table>';
	}
}

include 'footer.php';
?>
