<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();

$id = !empty($_GET['id']) ? (int)$_GET['id'] : null;
$post = null;
if ($id) {
    $stmt = db()->prepare('SELECT * FROM blog_posts WHERE id = ?');
    $stmt->execute([$id]);
    $post = $stmt->fetch();
    if (!$post) { header('Location: /admin/blog.php'); exit; }
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check()) $errors[] = 'Session expired, please try again.';
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '') ?: preg_replace('/[^a-z0-9]+/', '-', strtolower($title));
    $slug = trim($slug, '-');

    $uploadedCover = null;
    if (!empty($_FILES['cover_image']['tmp_name']) && is_uploaded_file($_FILES['cover_image']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) {
            $dir = __DIR__ . '/../assets/images/blog/';
            $filename = 'post-' . time() . '.' . $ext;
            move_uploaded_file($_FILES['cover_image']['tmp_name'], $dir . $filename);
            $uploadedCover = 'assets/images/blog/' . $filename;
        }
    }

    if ($title === '') $errors[] = 'Title is required.';

    if (empty($errors)) {
        $fields = [
            'type' => in_array($_POST['type'] ?? '', ['article', 'news'], true) ? $_POST['type'] : 'article',
            'title' => $title, 'slug' => $slug,
            'category' => trim($_POST['category'] ?? ''),
            'excerpt' => trim($_POST['excerpt'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'cover_image' => $uploadedCover ?: ($post['cover_image'] ?? 'assets/images/blog/news-1.jpg'),
            'author' => trim($_POST['author'] ?? 'Kigali Yacu Properties'),
            'meta_title' => trim($_POST['meta_title'] ?? ''),
            'meta_description' => trim($_POST['meta_description'] ?? ''),
            'published_at' => trim($_POST['published_at'] ?? date('Y-m-d')) . ' 09:00:00',
        ];

        if ($post) {
            $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($fields)));
            db()->prepare("UPDATE blog_posts SET $set WHERE id = :id")->execute($fields + ['id' => $post['id']]);
            $postId = $post['id'];
        } else {
            $cols = implode(', ', array_keys($fields));
            $ph = implode(', ', array_map(fn($k) => ":$k", array_keys($fields)));
            db()->prepare("INSERT INTO blog_posts ($cols) VALUES ($ph)")->execute($fields);
            $postId = (int)db()->lastInsertId();
        }
        flash_set('success', 'Post saved.');
        header('Location: /admin/blog-edit.php?id=' . $postId);
        exit;
    }
}

$pageTitle = $post ? 'Edit Post' : 'Add Post';
include __DIR__ . '/includes/layout-header.php';
$flash = flash_get('success');
?>
<?php if ($flash): ?><div class="form-success mb-6"><?= e($flash) ?></div><?php endif; ?>
<?php foreach ($errors as $err): ?><div class="form-error mb-4"><?= e($err) ?></div><?php endforeach; ?>

<form method="post" enctype="multipart/form-data" class="admin-card">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <div class="field-row mb-4">
    <div class="field"><label>Title</label><input type="text" name="title" value="<?= e($post['title'] ?? '') ?>" required></div>
    <div class="field"><label>Slug</label><input type="text" name="slug" value="<?= e($post['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field">
      <label>Type</label>
      <select name="type">
        <option value="article" <?= ($post['type'] ?? '') === 'article' ? 'selected' : '' ?>>Blog Article</option>
        <option value="news" <?= ($post['type'] ?? '') === 'news' ? 'selected' : '' ?>>News / Company Update</option>
      </select>
    </div>
    <div class="field"><label>Category</label><input type="text" name="category" value="<?= e($post['category'] ?? '') ?>"></div>
    <div class="field"><label>Published Date</label><input type="date" name="published_at" value="<?= e($post ? date('Y-m-d', strtotime($post['published_at'])) : date('Y-m-d')) ?>"></div>
  </div>
  <div class="field mb-4"><label>Excerpt</label><textarea name="excerpt" rows="2"><?= e($post['excerpt'] ?? '') ?></textarea></div>
  <div class="field mb-4">
    <label>Content (HTML — use &lt;h2&gt; for sections, they auto-generate the table of contents)</label>
    <textarea name="content" rows="16"><?= e($post['content'] ?? '') ?></textarea>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Author</label><input type="text" name="author" value="<?= e($post['author'] ?? 'Kigali Yacu Properties') ?>"></div>
    <div class="field"><label>Cover Image</label><input type="file" name="cover_image" accept="image/*"></div>
  </div>
  <?php if (!empty($post['cover_image'])): ?>
    <div class="media-frame rounded-md aspect-video mb-4" style="max-width:320px;"><img src="/<?= e($post['cover_image']) ?>" alt="" width="320" height="180"></div>
  <?php endif; ?>
  <div class="field mb-4"><label>Meta Title</label><input type="text" name="meta_title" value="<?= e($post['meta_title'] ?? '') ?>"></div>
  <div class="field mb-6"><label>Meta Description</label><textarea name="meta_description" rows="2"><?= e($post['meta_description'] ?? '') ?></textarea></div>
  <button type="submit" class="btn btn-primary btn-lg">Save Post</button>
</form>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
