<!--  -->


<?php

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

/*
|------------------------------------------------------------------
| 1. Determine which post we’re editing.
|   – On first load: use  ?id=... from GET
|   – On form submit: use  post_id from POST
|------------------------------------------------------------------
*/
$postId      = isset($_POST['post_id']) ? $_POST['post_id'] : (isset($_GET['id']) ? $_GET['id'] : '');
$foundIndex  = -1;

foreach ($posts as $index => $p) {
    if (isset($p['id']) && $p['id'] === $postId) {
        $foundIndex = $index;
        break;
    }
}

if ($foundIndex === -1) {
    echo 'Post not found.';
    exit;
}

$post = $posts[$foundIndex];

/*
|------------------------------------------------------------------
| 2. Handle form submission (update in place, no new post added)
|------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $posts[$foundIndex]['title']        = isset($_POST['title'])        ? $_POST['title']        : '';
    $posts[$foundIndex]['author']       = isset($_POST['author'])       ? $_POST['author']       : 'Admin';
    $posts[$foundIndex]['published_at'] = isset($_POST['published_at']) ? $_POST['published_at'] : date('Y-m-d H:i');
    $posts[$foundIndex]['summary']      = isset($_POST['summary'])      ? $_POST['summary']      : '';
    $posts[$foundIndex]['tags']         = array_map('trim', explode(',', isset($_POST['tags']) ? $_POST['tags'] : ''));
    $posts[$foundIndex]['content']      = isset($_POST['content'])      ? $_POST['content']      : '';

    // optional image replacement
    if (!empty($_FILES['image']['name'])) {
        $uploadDir = __DIR__ . '/../uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $imageName = time() . '_' . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $imageName)) {
            $posts[$foundIndex]['imageurl'] = 'uploads/' . $imageName;
        }
    }

    file_put_contents($postsFile, json_encode($posts, JSON_PRETTY_PRINT));
    header('Location: dashboard.php');
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Edit Post</title>
    <link rel="stylesheet" href="assets/style.css">
  <script src="assets/tinymce/js/tinymce/tinymce.min.js"></script>
    <script>
        tinymce.init({
            selector: 'textarea#content',
            height: 300,
            menubar: false,
            plugins: 'link image code lists',
            toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright | bullist numlist | link image | code',
            setup: ed => ed.on('change', () => ed.save())   // keep <textarea> synced
        });
    </script>
    <style>
        body{font-family:Arial;padding:20px;max-width:800px;margin:auto}
        label{font-weight:bold;display:block;margin-top:15px}
        input,textarea{width:100%;padding:8px;margin-bottom:10px}
        button{padding:10px 20px;background:#28a745;color:#fff;border:none;border-radius:5px}
        img.preview{max-width:100%;max-height:250px;margin-bottom:10px}
    </style>
</head>
<body>
<h2>Edit Post</h2>

<form method="POST" enctype="multipart/form-data">
    <!-- hidden field keeps the unique post id -->
    <input type="hidden" name="post_id" value="<?= htmlspecialchars($post['id']) ?>">

    <label>Title</label>
    <input type="text" name="title" value="<?= htmlspecialchars($post['title']) ?>" required>

    <label>Author</label>
    <input type="text" name="author" value="<?= htmlspecialchars($post['author']) ?>">

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

    <label>Summary</label>
    <textarea name="summary" rows="3"><?= htmlspecialchars($post['summary']) ?></textarea>

    <label>Tags (comma‑separated)</label>
    <input type="text" name="tags" value="<?= htmlspecialchars(implode(', ', $post['tags'])) ?>">

    <label>Content</label>
    <textarea id="content" name="content"><?= htmlspecialchars($post['content']) ?></textarea>

    <label>Image</label>
    <?php if (!empty($post['imageurl'])): ?>
        <img src="../<?= htmlspecialchars($post['imageurl']) ?>" class="preview" alt="current image">
    <?php endif; ?>
    <input type="file" name="image" accept="image/*">

    <button type="submit">Update Post</button>
</form>
</body>
</html>
