<?php

    include("json.php");

    $db = new PDO(
        "mysql:host=localhost;dbname=class_blog",
        "class_user",
        "class_password"
    );

    if ($_GET['direction'] == 'prev')
    {
        $query = "
            SELECT * FROM `posts`
            WHERE `postid` < :postid
            AND `username` = :username
            ORDER BY `postid` DESC
        ";
        $params = array(
            ':postid' => $_GET['postid'],
            ':username' => $_GET['username']
        );
    }
    else if ($_GET['direction'] == 'next')
    {
        $query = "
            SELECT * FROM `posts`
            WHERE `postid` > :postid
            AND `username` = :username
            ORDER BY `postid` ASC
        ";
        $params = array(
            ':postid' => $_GET['postid'],
            ':username' => $_GET['username']
        );
    }
    else
    {
        $query = "
            SELECT * FROM `posts`
            WHERE `postid` = :postid
        ";
        $params = array(
            ':postid' => $_GET['postid'],
        );
    }

    // Get either the next post, the previous post, or a given
    // post (depending on direction)
    $get_post_query = $db->prepare($query);
    $get_post_query->execute($params);
    $post = $get_post_query->fetch();

    // Comments from whichever post we fetched
    $get_comments_query = $db->prepare("
        SELECT * FROM `comments`
        WHERE postid = :postid
        ORDER BY `comment_date` DESC
    ");

    $get_comments_query->execute(array(
        ':postid' => $post['postid']
    ));

    // Get all comments and stuff them into $post
    $post['comments'] = $get_comments_query->fetchAll();

    // Encode in JSON and display
    echo pretty_json_encode($post);

?>
