<?php

session_start();

if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
} else {
    header('Location: login.php');
    die();
}

if (isset($_POST['logoutButton'])) {
    session_unset();
    session_destroy();
    header('Location: login.php');
}

if (isset($_POST['addNewsButton'])) {
    header('Location: ../News/addNews.php');
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Admin page</title>
</head>

<body>
    <div class="container text-center">
        <h3>Welcome, <?php echo $username; ?>!</h3>
        <table class="container" id="newsTable"
            style="margin: 30px; border: 1px solid;border-color: black; border-collapse: collapse;">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Content</th>
                    <th>Category</th>
                    <th>Date</th>
                    <th>Producer</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php
                require_once '../../Repositories/Repository.php';
                $connection = new DBConnection();
                $result = $connection->getAllNews();
                foreach ($result as $key => $value) {
                    echo "<tr>";
                    echo "<td>" . $value['title'] . "</td>";
                    echo "<td>" . $value['news_text'] . "</td>";
                    echo "<td>" . $value['category'] . "</td>";
                    echo "<td>" . $value['date'] . "</td>";
                    echo "<td>" . $value['producer'] . "</td>";
                    echo "<td><a href='../News/editNews.php?id=" . $value['id'] . "'>Edit</a></td>";
                    echo "</tr>";
                }
                ?>
            </tbody>
            <form method="post">
                <input type="submit" class="btn btn-primary" name="addNewsButton" value="Add news" style="margin: 30px">
                <input type="submit" class="btn btn-dark" name="logoutButton" value="Log out" style="margin: 30px">
            </form>
    </div>
</body>

</html>