<?php
session_start();
if (!isset($_SESSION["user"])) {
    header("Location: login.php");
    exit;
}

$books = json_decode(file_get_contents("data/books.json"), true);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $file = "data/reviews.json";
    $reviews = json_decode(file_get_contents($file), true);

    $reviews[] = [
        "book" => htmlspecialchars($_POST["book"]),
        "text" => htmlspecialchars($_POST["text"]),
        "rating" => (int)$_POST["rating"],
        "date" => date("d.m.Y")
    ];

    file_put_contents($file, json_encode($reviews, JSON_PRETTY_PRINT));
    header("Location: index.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="UTF-8">
<title>Adaugă recenzie</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js" defer></script>
</head>
<body>

<header class="site-header">
    <div class="logo">BookReviews</div>

    <button class="menu-toggle" id="menuToggle">☰</button>

    <nav class="nav" id="navMenu">
        <a href="index.php">Acasă</a>
        <a href="library.php">Bibliotecă</a>

        <?php if (isset($_SESSION["user"])): ?>
            <a href="add-review.php">Adaugă recenzie</a>
            <a href="logout.php">
                Logout (<?= htmlspecialchars($_SESSION["user"]) ?>)
            </a>
        <?php else: ?>
            <a href="login.php">Login</a>
        <?php endif; ?>
    </nav>
</header>


<main class="login-page">
    <section class="login-card review-add-card">
        <h2>Adaugă recenzie</h2>
        <p class="login-subtitle">Completează formularul pentru a publica o recenzie nouă</p>

        <form method="post" id="reviewForm">
            <label for="book">Carte</label>
            <select name="book" id="book">
                <?php foreach ($books as $b): ?>
                    <option><?= $b["title"] ?></option>
                <?php endforeach; ?>
            </select>

            <label for="reviewText">Recenzie</label>
            <textarea name="text" id="reviewText" maxlength="300"></textarea>
            <div id="charCount">0 / 300</div>

            <label for="rating">Rating</label>
            <select name="rating" id="rating">
                <option value="">Alege rating</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

            <p id="formError" class="error"><?= htmlspecialchars($error ?? "") ?></p>

            <button type="submit" class="login-btn">Salvează</button>
        </form>
    </section>
</main>

</body>
</html>
