<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/helpers.php';
require_admin();

$posts = [];
try {
    $posts = db()->query('SELECT id, title, slug, status, created_at FROM posts ORDER BY created_at DESC')->fetchAll();
} catch (Throwable $e) {
    $posts = [];
}

$css = nestor_asset_url('assets/css/style.css');
echo '<!doctype html><html lang="uk"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Адмінка блогу</title><link rel="stylesheet" href="' . e($css) . '"></head><body>';
echo '<main id="main-content" class="section"><div class="wrap">';
echo '<div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:1rem;align-items:center;margin-bottom:1.5rem">';
echo '<h1>Пости</h1><div class="btn-row" style="margin:0">';
echo '<a class="btn btn--ghost" href="' . e(nestor_url('blog.php')) . '" target="_blank" rel="noopener">Відкрити блог</a>';
echo '<a class="btn btn--primary" href="post-create.php">Додати пост</a>';
echo '<a class="btn btn--ghost" href="logout.php">Вийти</a>';
echo '</div></div>';

if ($posts === []) {
    echo '<p class="prose-muted">Немає постів або база даних ще не підключена. Імпортуйте database/schema.sql.</p>';
} else {
    echo '<div class="price-card" style="overflow-x:auto;padding:0">';
    echo '<table style="width:100%;border-collapse:collapse;font-size:.92rem">';
    echo '<thead><tr style="border-bottom:1px solid var(--line);text-align:left">';
    echo '<th style="padding:.75rem 1rem">Заголовок</th><th style="padding:.75rem">Slug</th><th style="padding:.75rem">Статус</th><th style="padding:.75rem">Дата</th><th style="padding:.75rem">Дії</th>';
    echo '</tr></thead><tbody>';
    foreach ($posts as $post) {
        echo '<tr style="border-bottom:1px solid var(--line)">';
        echo '<td style="padding:.65rem 1rem">' . e($post['title']) . '</td>';
        echo '<td style="padding:.65rem">' . e($post['slug']) . '</td>';
        echo '<td style="padding:.65rem">' . e($post['status']) . '</td>';
        echo '<td style="padding:.65rem">' . e(date('d.m.Y', strtotime($post['created_at']))) . '</td>';
        echo '<td style="padding:.65rem"><a href="post-edit.php?id=' . (int)$post['id'] . '">Редагувати</a> · ';
        echo '<form style="display:inline" method="post" action="post-delete.php" onsubmit="return confirm(\'Видалити пост?\')">';
        echo '<input type="hidden" name="csrf" value="' . e(csrf_token()) . '">';
        echo '<input type="hidden" name="id" value="' . (int)$post['id'] . '">';
        echo '<button type="submit" style="border:0;background:none;color:#8b4040;cursor:pointer;padding:0;font:inherit">Видалити</button>';
        echo '</form></td></tr>';
    }
    echo '</tbody></table></div>';
}

echo '</div></main></body></html>';
