<?php

# [ index.php ]
# This is the main page of the message board which lists all the threads.
# A row on the board is created for each row that exists in the MySQL threads table.

include ('includes/header.html');

# (Query 1) All the rows of the message board will be returned with this MySQL statement.
$q = "SELECT thread_id, thread_title, thread_author, thread_date FROM threads ORDER BY thread_date DESC";
$r = mysqli_query($dbc, $q);

# Only display the board if there are any threads.
if (mysqli_num_rows($r) > 0) {
	
	# Echo a link to create a new thread.
    echo '<p id="nt"><a href="newthread.php">New Thread</a></p>';
    # Echo the table header.
    echo '<table id="board">
		<tr><th id="titlehead">Title</th><th>Author</th><th>Date</th><th>Replies</th></tr>';
		# This loop displays all the rows of the message board.
    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
		
		# (Query 2) This block of code is used to determine how many people have replied to each thread.
		# It takes the number of posts and subtracts 1 (the initial post).
        $q2 = "SELECT in_thread FROM posts WHERE in_thread='{$row['thread_id']}'";
        $r2 = mysqli_query($dbc, $q2);
        $number = (mysqli_num_rows($r2) - 1);
		
		# (Query 3) This block of code is used to determine who created each thread.
        $q3 = "SELECT username FROM users WHERE user_id='{$row['thread_author']}'";
        $r3 = mysqli_query($dbc, $q3);
        $row3 = mysqli_fetch_array($r3);
		
		# Echo each row using the variables defined above.
        echo "<tr>
			<td><a href=\"thread.php?id={$row['thread_id']}\">{$row['thread_title']}</a></td>
			<td><a href=\"user.php?id={$row['thread_author']}\">" . ucwords($row3['username']) .
            "</a></td>
			<td><a href=\"thread.php?id={$row['thread_id']}\">" . formatdate($row['thread_date'], null) .
            "</a></td>
			<td><a href=\"thread.php?id={$row['thread_id']}\">$number</a></td>
			</tr>
			";

    }
    # Echo the end of the table.
    echo '</table>';

# If no threads are stored in the database.
} else {
    echo "Sorry, no threads exist!";
}

include ('includes/footer.html');

?>