<?php
declare(strict_types=1);

require_once __DIR__ . '/../lib.php';
session_start();

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'login') {
    verify_csrf();
    if (hash_equals(admin_password(), (string)($_POST['password'] ?? ''))) {
        $_SESSION['is_admin'] = true;
        header('Location: /admin/');
        exit;
    }
    $error = 'Неверный пароль.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'logout') {
    verify_csrf();
    $_SESSION = [];
    session_destroy();
    header('Location: /admin/');
    exit;
}

if (is_admin() && $_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    $id = (string)($_POST['id'] ?? '');
    $offers = read_json_file(OFFERS_FILE);
    $news = read_json_file(NEWS_FILE);

    if ($action === 'approve') {
        foreach ($offers as $index => $offer) {
            if (($offer['id'] ?? '') === $id) {
                $news[] = [
                    'id' => bin2hex(random_bytes(8)),
                    'title' => (string)($offer['title'] ?? ''),
                    'body' => (string)($offer['body'] ?? ''),
                    'author' => (string)($offer['author'] ?? 'Анонимно'),
                    'published_at' => (new DateTimeImmutable('now'))->format(DateTimeInterface::ATOM),
                ];
                unset($offers[$index]);
                write_json_file(NEWS_FILE, $news);
                write_json_file(OFFERS_FILE, $offers);
                $message = 'Новость опубликована.';
                break;
            }
        }
    }

    if ($action === 'reject') {
        $offers = array_values(array_filter($offers, static fn(array $offer): bool => ($offer['id'] ?? '') !== $id));
        write_json_file(OFFERS_FILE, $offers);
        $message = 'Заявка удалена.';
    }

    if ($action === 'delete_news') {
        $news = array_values(array_filter($news, static fn(array $item): bool => ($item['id'] ?? '') !== $id));
        write_json_file(NEWS_FILE, $news);
        $message = 'Новость снята с публикации.';
    }
}

$offers = read_json_file(OFFERS_FILE);
$news = sorted_news();
?>
<!doctype html>
<html lang="ru">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Админка · <?= h(SITE_NAME) ?></title>
    <link rel="stylesheet" href="/assets/style.css">
</head>
<body>
<header class="topbar">
    <div class="topbar__inner">
        <a class="brand" href="/"><?= h(SITE_NAME) ?></a>
        <nav class="nav" aria-label="Основная навигация">
            <a href="/">Новости</a>
            <a href="/offer/">Предложить новость</a>
            <a href="/admin/">Админка</a>
        </nav>
    </div>
</header>

<main class="wrap">
    <section class="hero">
        <span class="school-note">Панель редакции</span>
        <h1>Админка школьной ленты</h1>
        <p>Модерация предложенных школьных новостей и управление опубликованными материалами.</p>
    </section>

    <?php if (!is_admin()): ?>
        <section class="panel">
            <?php if ($error !== ''): ?>
                <p class="flash error"><?= h($error) ?></p>
            <?php endif; ?>
            <form method="post">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="login">
                <label>
                    Пароль администратора
                    <input type="password" name="password" required autocomplete="current-password">
                </label>
                <button type="submit">Войти</button>
                <p class="hint">Пароль задается в config.php или через ADMIN_PASSWORD.</p>
            </form>
        </section>
    <?php else: ?>
        <?php if ($message !== ''): ?>
            <p class="flash"><?= h($message) ?></p>
        <?php endif; ?>

        <form class="inline-form" method="post">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="logout">
            <button class="secondary" type="submit">Выйти</button>
        </form>

        <div class="admin-grid">
            <section>
                <h2>На модерации</h2>
                <div class="news-list">
                    <?php if ($offers === []): ?>
                        <article class="card empty">Новых заявок нет.</article>
                    <?php endif; ?>
                    <?php foreach (array_reverse($offers) as $offer): ?>
                        <article class="card">
                            <h3><?= h($offer['title'] ?? 'Без заголовка') ?></h3>
                            <div class="meta">
                                <?= h(format_date((string)($offer['created_at'] ?? ''))) ?>
                                · <?= h((string)($offer['author'] ?? 'Анонимно')) ?>
                                <?php if (!empty($offer['contact'])): ?>
                                    · <?= h((string)$offer['contact']) ?>
                                <?php endif; ?>
                            </div>
                            <div class="body-text"><?= h((string)($offer['body'] ?? '')) ?></div>
                            <div class="actions">
                                <form class="inline-form" method="post">
                                    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="approve">
                                    <input type="hidden" name="id" value="<?= h((string)$offer['id']) ?>">
                                    <button type="submit">Опубликовать</button>
                                </form>
                                <form class="inline-form" method="post">
                                    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="reject">
                                    <input type="hidden" name="id" value="<?= h((string)$offer['id']) ?>">
                                    <button class="danger" type="submit">Удалить</button>
                                </form>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>

            <section>
                <h2>Опубликовано</h2>
                <div class="news-list">
                    <?php if ($news === []): ?>
                        <article class="card empty">Публикаций нет.</article>
                    <?php endif; ?>
                    <?php foreach ($news as $item): ?>
                        <article class="card">
                            <h3><?= h($item['title'] ?? 'Без заголовка') ?></h3>
                            <div class="meta"><?= h(format_date((string)($item['published_at'] ?? ''))) ?></div>
                            <p><?= h(excerpt((string)($item['body'] ?? ''))) ?></p>
                            <form class="inline-form" method="post">
                                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="delete_news">
                                <input type="hidden" name="id" value="<?= h((string)$item['id']) ?>">
                                <button class="danger" type="submit">Снять</button>
                            </form>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>
        </div>
    <?php endif; ?>
</main>
</body>
</html>

