<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  
    $title = $_POST['title'] ?? '';
    $author = $_POST['author'] ?? 'Admin';
    $published_at = $_POST['published_at'] ?? date('Y-m-d H:i');
    $summary = $_POST['summary'] ?? '';
    $tags = array_map('trim', explode(',', $_POST['tags'] ?? ''));
    $content = $_POST['content'] ?? '';

    $imagePath = '';
    if (!empty($_FILES['image']['name'])) {
        $uploadDir = __DIR__ . '/../uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $imageName = time() . '_' . basename($_FILES['image']['name']);
        $imagePath = 'uploads/' . $imageName;
        move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $imageName);
    }

    $postsFile = __DIR__ . '/posts.json';
    $posts = file_exists($postsFile) ? json_decode(file_get_contents($postsFile), true) : [];

    $posts[] = [
        'id' => 'm' . count($posts),
        'title' => $title,
        'author' => $author,
        'published_at' => $published_at,
        'summary' => $summary,
        'tags' => $tags,
        'content' => $content,
        'imageurl' => $imagePath
    ];

    file_put_contents($postsFile, json_encode($posts, JSON_PRETTY_PRINT));
    header('Location: dashboard.php');
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Create New Post</title>
  <link rel="stylesheet" href="assets/style.css">
  <script src="assets/tinymce/js/tinymce/tinymce.min.js"></script>
  <script>
    tinymce.init({
      selector: 'textarea#editor',
      height: 300,
      menubar: false,
      plugins: 'link image code lists',
      toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright | bullist numlist | link image | code'
    });
  </script>
  <style>
    body { font-family: Arial; padding: 20px; max-width: 800px; margin: auto; }
    input, textarea { width: 100%; padding: 8px; margin-bottom: 10px; }
    label { font-weight: bold; display: block; margin-top: 15px; }
    button { padding: 10px 20px; background: #007bff; color: #fff; border: none; border-radius: 5px; }
  </style>
</head>
<body>

<h2>Create New Post</h2> 
<a href="dashboard.php">← Back to Dashboard</a> <hr>

<form method="POST" enctype="multipart/form-data">
  <label>Title</label>
  <input type="text" name="title" required>

  <label>Author</label>
  <input type="text" name="author" value="Admin">

  <label>Date Published</label>
  <input type="datetime-local" name="published_at" value="<?= date('Y-m-d\TH:i') ?>">

  <label>Summary (short excerpt)</label>
  <textarea name="summary" rows="3" required></textarea>

  <label>Tags (comma-separated)</label>
  <input type="text" name="tags" placeholder="e.g. bitcoin, ethereum, crypto news">

  <label>Content</label>
  <textarea id="editor" name="content" ></textarea>

  <label>Image</label>
  <input type="file" name="image" accept="image/*">

  <button type="submit">Publish Post</button>
</form>

</body>
</html>
