<?php

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

    // CSRF: Make sure that the user sent back the
    // canary we told them to. Does it match the one
    // we stored for them in their session?
    if ($_POST['canary'] != $_SESSION['canary'])
    {
        die("CSRF attack");
    }

    // Connect to the database and add a message
    include("connect.php"); 

    $add_message_query = $db->prepare("
        INSERT INTO `messages`
            (`username`, `time`, `message`)
        VALUES
            (:username, CURRENT_TIMESTAMP, :text)
    ");

    $add_message_query->execute(array(
        ':username' => $_SESSION['username'],
        ':text'     => $_POST['message']
    ));

    // This calls for a '301' response code instead of '200', with a 'Location'
    // sent to tell the browser where to redirect to.
    header("Location: chat.php");

?>
