<?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();

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    header('Location: dashboard.php');
    exit;
}

$post = null;
try {
    $stmt = db()->prepare('SELECT id, title, slug, content, status FROM posts WHERE id = :id LIMIT 1');
    $stmt->execute(['id' => $id]);
    $post = $stmt->fetch();
} catch (Throwable $e) {
    $post = null;
}
if (!$post) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? null)) {
        $error = 'Невірний CSRF токен.';
    } else {
        $title = trim((string)($_POST['title'] ?? ''));
        $slug = trim((string)($_POST['slug'] ?? ''));
        $content = sanitize_post_html(trim((string)($_POST['content'] ?? '')));
        $status = ($_POST['status'] ?? 'draft') === 'published' ? 'published' : 'draft';

        $slugOk = preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1;
        if ($title === '' || $slug === '' || $content === '') {
            $error = 'Заповніть усі обовʼязкові поля.';
        } elseif (!$slugOk) {
            $error = 'Slug: лише латинські літери, цифри та дефіс.';
        } else {
            try {
                $update = db()->prepare('UPDATE posts SET title = :title, slug = :slug, content = :content, status = :status WHERE id = :id');
                $update->execute(['title' => $title, 'slug' => $slug, 'content' => $content, 'status' => $status, 'id' => $id]);
                header('Location: dashboard.php');
                exit;
            } catch (Throwable $e) {
                $error = 'Не вдалося оновити (можливо, slug зайнятий).';
            }
        }
    }
}

$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" style="max-width:860px">';
echo '<h1 style="margin-bottom:1rem">Редагувати пост</h1>';
if ($error !== '') {
    echo '<p style="color:#8b4040;margin-bottom:1rem">' . e($error) . '</p>';
}
echo '<form class="price-card contact-form" style="max-width:none;padding:clamp(1.25rem,3vw,2rem)" method="post">';
echo '<input type="hidden" name="csrf" value="' . e(csrf_token()) . '">';
echo '<p><label>Заголовок<input required name="title" value="' . e((string)$post['title']) . '"></label></p>';
echo '<p><label>Slug<input required name="slug" value="' . e((string)$post['slug']) . '"></label></p>';
echo '<p><label>Статус<select name="status"><option value="draft"' . (($post['status'] === 'draft') ? ' selected' : '') . '>Чернетка</option><option value="published"' . (($post['status'] === 'published') ? ' selected' : '') . '>Опубліковано</option></select></label></p>';
echo '<p><label>Текст (HTML)<textarea required name="content" rows="16">' . e((string)$post['content']) . '</textarea></label></p>';
echo '<div class="btn-row"><button class="btn btn--primary" type="submit">Оновити</button><a class="btn btn--ghost" href="dashboard.php">Назад</a></div>';
echo '</form></div></main></body></html>';
