<?php
    include_once("../includes/config.php");

    function generateRandomString($length = 11) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    $postUrlGen = generateRandomString();

    // check if the user is logged in
    if(!$_SESSION["username"]) {
        header("Location: ../login.php");
    }

    // check if the request is a post request
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(isset($_POST["postSubmit"])) {
            // declare variables
            $postBody = htmlspecialchars(strip_tags($_POST["postBodyInput"]));
            $author = "winsdominoes";

            // check if the post body is empty
            if(!$postBody) {
                die("No post body was entered");
            }
            
            // pdo prepare statement
            $stmt = $con->prepare("INSERT INTO posts (url, content, author) VALUES (:url, :content, :author)");
            $stmt->bindParam(":url", $postUrlGen);
            $stmt->bindParam(":content", $postBody);
            $stmt->bindParam(":author", $author);
            $stmt->execute();

            // check if query was successful
            if($stmt) {
                header("Location: ../index.php");
            } else {
                die("Something went wrong");
            }
        }
    }
    
?>