<?php

    include("connect.php");

    // Make sure the user is logged in:
    session_name('chat_hw10');
    session_start();
    if (empty($_SESSION['username']))
    {
        header("Location: login.php");
        exit;
    }

    // CSRF prevention: if we don't have a canary yet, let's
    // generate one! Just a random string of letters and numbers.
    if (!isset($_SESSION['canary']))
    {
        $_SESSION['canary'] = generate_salt(32);
    }

    $get_messages_query = $db->prepare("
        SELECT * FROM `messages`
        ORDER BY `messageid` ASC
    ");
    $get_messages_query->execute();

    while ($row = $get_messages_query->fetch())
    {
        $chat_history_html .=
            '<div class="message">
                <span class="date">' . $row['time'] . '</span>
                <span class="user">' . $row['username'] . '</span>
                <span class="text">' .
                    htmlspecialchars($row['message']) .
                '</span>
            </div>';
    }

?>

<!doctype html>
<html>
    <head>
        <title>Forever Alone Chat</title>
        <link type="text/css" rel="stylesheet" href="alone.css" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script type="text/javascript" src="alone.js"></script>
    </head>

    <body>

        <div id="header">Not-So-Alone-Anymore Chat</div>

        <div id="container">
            <div id="history">
            <?=$chat_history_html?>
            </div>

            <div id="textbox">
                <form method="post" action="savemessage.php">
                    <!-- Put CSRF canary into form so it gets submitted -->
                    <input type="hidden"
                        name="canary"
                        value="<?=$_SESSION['canary']?>" />
                    <input type="text" id="message" name="message"
                        autocomplete="off" required autofocus />
                    <input type="submit" value="send" />
                    <span id="loading">
                        <img src="loading.gif" style="height: 20px;" />
                    </span>
                </form>
            </div>
        </div>

    </body>

</html>
