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

$content = '[removed]';

//fetch the post from the database
$post_sql = "SELECT postBy
            FROM posts
            WHERE	postNo = ?";

$stmt = $conn->prepare($post_sql);
$stmt->bind_param('i', $_GET['post']);
$stmt->execute();
$post_result = $stmt->get_result();

if(!$post_result)
{
    echo 'The post could not be retrieved, please try again later.';
}
else
{
    if($_SERVER['REQUEST_METHOD'] != 'POST')
	{
        if(!$_SESSION['signedIn'])
        {
            echo 'You must be <a href="signin.php">signed in</a> to delete a post. You can also <a href="signup.php">sign up</a> for an account.';
        }
        else if ($_SESSION['userNo'] != $post_result->fetch_assoc()['postBy'])
        {
            echo 'You cannot edit this post. You are not OP!';
        }
        else
        {

            echo '<p>Are you sure you want to remove this post?</p>';

            //show edit form
            echo '<br />
                  <form method="post" action="">
                    <input type="hidden" name="postContent" value="' . htmlentities($content, ENT_QUOTES | ENT_HTML5, 'UTF-8') . '" />
                    <input type="submit" value="Yes" />
                  </form>
                  <form method="post" action="topic.php?id='. htmlentities($_GET['topic'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '">
                    <input type="Submit" value="No" />
                  </form>';
        }
    }
    else
    {
        //the form has been posted, now it's time to process.
        //start the transaction
        $query  = "BEGIN WORK;";

        if(!$conn->query($query))
        {
            //Damn! the query failed, quit
            echo 'An error occured while editing your post. Please try again later.';
        }
        else
        {
            //the form has been posted, so save it
            //update the post in the posts table then save it
            $update_sql = " UPDATE posts
                            SET postContent = ?
                            WHERE postNo = ?";

            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('si', $content, $_GET['post']);

            if(!$update_stmt->execute())
            {
                //something went wrong, display the error
                echo 'An error occured while inserting your data. Please try again later.<br /><br />' . $conn->error;
                $sql = "ROLLBACK;";
                $conn->query($sql);
            }
            else
            {
                $sql = "COMMIT;";
                $conn->query($sql);

                //after a lot of work, the query succeeded!
                echo 'You have succesfully removed <a href="topic.php?id='. htmlentities($_GET['topic'], ENT_QUOTES | ENT_HTML5, 'UTF-8') . '">your post</a>.';
            }
        }
    }
}

include 'footer.php';
?>
