<?php

if ($_SERVER["REQUEST_METHOD"] === 'POST') {
    $newTweet = new Tweet();
    $newTweet->createTweet($conn, $_SESSION["user_id"], $_POST["tweet"]);
}
?>
<hr>
<form method="post" action="#" style="padding: 20px">
    <label>CREATE NEW TWEET</label><br>
    <textarea name="tweet" placeholder="Enter tweet here"></textarea><br>
    <label></label><br>
    <input type="submit" value="Tweet">
</form>
<hr>
            <table class="table table-hover">
                <thead>
                <?php 
echo "<H2>Hello {$myUser->getEmail()}</H2>\n                    <h4> Have nice day !!!</h4>";
?>
                <tr>
                    <th>User Name</th>
                    <th>Dweet</th>
                    <th>Date</th>

                </tr>
                </thead>
                <tbody>
                <?php 
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST)) {
    Tweet::createTweet($myUser->getId(), $_POST['tweet']);
}
$allTweets = Tweet::loadAllTweets();
foreach ($allTweets as $tweet) {
    echo "\n                <tr>\n\n                    <td>";
    $sql = "SELECT * FROM Users WHERE user_id = '{$tweet->getuserId()}';";
    $result = $conn->query($sql);
    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        echo $row['email'];
    }
    echo "\n                    <br> </td>\n                    <td>{$tweet->getText()}<br> </td>\n                    <td> {$tweet->getCreateDate()}<br></td>\n\n                </tr>";
}
?>
                </tbody>
            </table>
<?php

require_once "functions/function.inputSanitizer.inc.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tweetText'])) {
    $tweet = new Tweet($conn);
    if (strlen($_POST['tweetText']) > 140) {
        echo "Twój tweet jest za długi";
    } else {
        if (!$tweet->createTweet($user->getId(), sanitizeMySQL($conn, $_POST['tweetText']))) {
            echo "BŁĄD!";
        }
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['commentText'])) {
    if (strlen($_POST['commentText']) > 5) {
        $comment = new Comment($conn);
        $comment->createComment($user->getId(), sanitizeMySQL($conn, $_POST['tweetID']), sanitizeMySQL($conn, $_POST['commentText']));
    } else {
        echo "Twój komentarz jest za krótki";
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tweetDelete'])) {
    $tweet = new Tweet($conn);
    $tweet->loadFromDB(sanitizeMySQL($conn, $_POST['tweetDelete']));
    $tweet->deleteTweet();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['commentDelete'])) {
    $comment = new Comment($conn);
    $comment->loadFromDB(sanitizeMySQL($conn, $_POST['commentDelete']));
    $comment->deleteComment();
}