<?php
// ============================================================
//  Admin — Blog post edit / add
//  POST processing happens before _guard.php to allow redirects
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_admin();

$post_id = (int)($_GET['id'] ?? 0);
$action  = $_GET['action'] ?? 'edit';
$is_add  = ($action === 'add');

$post   = null;
$errors = [];

if (!$is_add) {
    $post = db_row('SELECT * FROM blog_posts WHERE id=:id', ['id'=>$post_id]);
    if (!$post) { http_response_code(404); echo 'Post not found.'; exit; }
}

// ── Slug helper ──────────────────────────────────────────────
function blog_slug(string $title, ?int $exclude_id = null): string {
    $base = preg_replace('/[^a-z0-9]+/', '-', strtolower($title));
    $base = trim($base, '-') ?: 'post';
    $slug = $base; $n = 2;
    while (true) {
        $existing = db_row('SELECT id FROM blog_posts WHERE slug=:s', ['s'=>$slug]);
        if (!$existing || (int)$existing['id'] === (int)$exclude_id) break;
        $slug = $base.'-'.$n++;
    }
    return $slug;
}

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $title      = trim($_POST['title']     ?? '');
    $excerpt    = trim($_POST['excerpt']   ?? '');
    $body       = trim($_POST['body']      ?? '');
    $author     = trim($_POST['author']    ?? '');
    $tags       = trim($_POST['tags']      ?? '');
    $posted_at  = trim($_POST['posted_at'] ?? date('Y-m-d'));
    $published  = !empty($_POST['published']) ? 1 : 0;
    $custom_slug= trim($_POST['slug']      ?? '');

    if (!$title)  $errors[] = 'Title is required.';
    if (!$body)   $errors[] = 'Body content is required.';
    if ($custom_slug && !preg_match('/^[a-z0-9\-]+$/', $custom_slug)) {
        $errors[] = 'Slug may only contain lowercase letters, numbers, and hyphens.';
    }

    // Cover image upload
    $cover_image = $post['cover_image'] ?? null;
    if (!empty($_FILES['cover_image']['name'])) {
        $file    = $_FILES['cover_image'];
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        $max     = 3 * 1024 * 1024;
        if (!in_array($file['type'], $allowed, true)) {
            $errors[] = 'Cover image must be JPG, PNG, GIF, or WebP.';
        } elseif ($file['size'] > $max) {
            $errors[] = 'Cover image must be under 3MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Cover image upload failed.';
        } else {
            $dir = __DIR__ . '/../assets/uploads/blog/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name = 'blog-' . time() . '-' . bin2hex(random_bytes(3)) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $dir . $name)) {
                // Delete old cover
                if ($cover_image) {
                    $old = __DIR__ . '/../' . ltrim($cover_image, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $cover_image = 'assets/uploads/blog/' . $name;
            } else {
                $errors[] = 'Could not save cover image. Check folder permissions.';
            }
        }
    }

    // Remove cover image if requested
    if (!empty($_POST['remove_cover']) && $cover_image) {
        $old = __DIR__ . '/../' . ltrim($cover_image, '/');
        if (file_exists($old)) @unlink($old);
        $cover_image = null;
    }

    if (empty($errors)) {
        $slug = $custom_slug ?: blog_slug($title, $post_id ?: null);

        $data = [
            'title'       => $title,
            'slug'        => $slug,
            'excerpt'     => $excerpt ?: null,
            'body'        => $body,
            'author'      => $author ?: null,
            'tags'        => $tags   ?: null,
            'cover_image' => $cover_image,
            'posted_at'   => $posted_at,
            'published'   => $published,
        ];

        if ($is_add) {
            db_insert('blog_posts', $data);
            header('Location: blog.php?msg='.urlencode('Post published!')); exit;
        } else {
            db_update('blog_posts', $post_id, $data);
            header('Location: blog-edit.php?id='.$post_id.'&msg=saved'); exit;
        }
    }

    // Re-populate on error
    $post = array_merge($post ?? [], [
        'title'      => $title,  'excerpt'   => $excerpt,
        'body'       => $body,   'author'    => $author,
        'tags'       => $tags,   'posted_at' => $posted_at,
        'published'  => $published, 'slug'   => $custom_slug,
        'cover_image'=> $cover_image,
    ]);
}

// Default values
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $post = $post ?? [
        'title'=>'','slug'=>'','excerpt'=>'','body'=>'','author'=>'',
        'tags'=>'','posted_at'=>date('Y-m-d'),'published'=>1,'cover_image'=>null,
    ];
}

$page_title = $is_add ? 'New post' : 'Edit — ' . ($post['title'] ?? '');
require __DIR__ . '/_guard.php';
?>

<style>
.blog-layout{display:grid;grid-template-columns:1fr 300px;gap:1.25rem;align-items:start;}
.b-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.25rem;margin-bottom:1.25rem;}
.b-card h2{margin:0 0 1rem;font-size:.95rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);}

/* TipTap / rich text editor */
.editor-toolbar{display:flex;flex-wrap:wrap;gap:.25rem;padding:.5rem;
                border:1px solid var(--line);border-bottom:none;border-radius:var(--radius) var(--radius) 0 0;
                background:var(--surface-alt);}
.editor-toolbar button{padding:.25rem .5rem;border:1px solid var(--line);background:#fff;
                        border-radius:3px;cursor:pointer;font-size:.8rem;line-height:1.4;
                        color:var(--ink);transition:background .15s;}
.editor-toolbar button:hover{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.editor-toolbar button.active{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.editor-toolbar .sep{width:1px;background:var(--line);margin:.1rem .2rem;align-self:stretch;}
#editor-content{min-height:380px;border:1px solid var(--line);
                border-radius:0 0 var(--radius) var(--radius);
                padding:1rem;outline:none;font-size:.95rem;line-height:1.7;}
#editor-content:focus{border-color:var(--brand-primary);}
#editor-content h2{font-size:1.4rem;margin:1.25rem 0 .5rem;}
#editor-content h3{font-size:1.1rem;margin:1rem 0 .4rem;}
#editor-content p{margin:0 0 .85rem;}
#editor-content ul,#editor-content ol{padding-left:1.5rem;margin:0 0 .85rem;}
#editor-content blockquote{border-left:3px solid var(--brand-primary);
                             padding-left:1rem;color:var(--ink-muted);margin:1rem 0;}
#editor-content a{color:var(--brand-primary);}
#editor-content img{max-width:100%;border-radius:4px;margin:.5rem 0;}

.upload-zone{border:2px dashed var(--line);border-radius:var(--radius);padding:1.25rem;
             text-align:center;cursor:pointer;position:relative;transition:border-color .2s,background .2s;}
.upload-zone:hover,.upload-zone.dragover{border-color:var(--brand-primary);background:rgba(34,139,34,.03);}
.upload-zone input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.cover-preview{width:100%;height:140px;object-fit:cover;border-radius:4px;
               margin-bottom:.5rem;border:1px solid var(--line);}

@media(max-width:900px){.blog-layout{grid-template-columns:1fr;}}
</style>

<section class="section">
<div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.1rem;">
    <div>
        <p class="muted" style="margin:0;"><a href="blog.php">← All posts</a></p>
        <h1 style="margin:.25rem 0 0;"><?= $is_add ? 'New post' : 'Edit post' ?></h1>
    </div>
    <?php if (!$is_add && !empty($post['slug'])): ?>
        <a href="../blog-post.php?id=<?= $post_id ?>" target="_blank" class="btn btn-outline">
            View live post ↗
        </a>
    <?php endif; ?>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-bottom:1rem;">
        <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
    </div>
<?php endif; ?>
<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide>Post saved.</div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data"
      action="blog-edit.php?<?= $is_add?'action=add':'id='.$post_id ?>">
    <?= csrf_field() ?>

    <div class="blog-layout">

        <!-- ── Main content column ── -->
        <div>
            <div class="b-card">
                <label style="font-weight:600;font-size:.88rem;display:block;margin-bottom:.4rem;">
                    Title *
                </label>
                <input type="text" name="title" id="post-title" required
                       value="<?= htmlspecialchars($post['title'] ?? '') ?>"
                       placeholder="Post title"
                       style="font-size:1.2rem;font-weight:600;width:100%;">

                <div style="margin-top:.75rem;">
                    <label style="font-weight:600;font-size:.88rem;display:block;margin-bottom:.4rem;">
                        Slug
                        <span class="muted" style="font-weight:400;">(auto-generated from title if blank)</span>
                    </label>
                    <div style="display:flex;align-items:center;gap:.4rem;">
                        <span class="muted" style="font-size:.85rem;white-space:nowrap;">
                            /blog-post.php?slug=
                        </span>
                        <input type="text" name="slug" id="post-slug"
                               value="<?= htmlspecialchars($post['slug'] ?? '') ?>"
                               placeholder="auto" style="flex:1;">
                    </div>
                </div>
            </div>

            <!-- Rich text body -->
            <div class="b-card" style="padding:0;overflow:hidden;">
                <div style="padding:.75rem 1.25rem;border-bottom:1px solid var(--line);background:var(--surface-alt);">
                    <strong style="font-size:.88rem;">Content *</strong>
                </div>
                <!-- Toolbar -->
                <div class="editor-toolbar" id="toolbar">
                    <button type="button" data-cmd="bold"        title="Bold"><b>B</b></button>
                    <button type="button" data-cmd="italic"      title="Italic"><i>I</i></button>
                    <button type="button" data-cmd="underline"   title="Underline"><u>U</u></button>
                    <div class="sep"></div>
                    <button type="button" data-cmd="h2"          title="Heading 2">H2</button>
                    <button type="button" data-cmd="h3"          title="Heading 3">H3</button>
                    <div class="sep"></div>
                    <button type="button" data-cmd="insertUnorderedList"  title="Bullet list">• List</button>
                    <button type="button" data-cmd="insertOrderedList"    title="Numbered list">1. List</button>
                    <button type="button" data-cmd="blockquote"           title="Blockquote">" Quote</button>
                    <div class="sep"></div>
                    <button type="button" data-cmd="createLink"  title="Insert link">🔗 Link</button>
                    <button type="button" data-cmd="insertImage" title="Insert image">🖼 Image</button>
                    <div class="sep"></div>
                    <button type="button" data-cmd="removeFormat" title="Clear formatting">✕ Format</button>
                </div>
                <!-- Editable area -->
                <div id="editor-content" contenteditable="true"></div>
                <!-- Hidden textarea synced to editor -->
                <textarea name="body" id="body-hidden" style="display:none;" required></textarea>
            </div>

            <!-- Excerpt -->
            <div class="b-card">
                <h2>Excerpt</h2>
                <textarea name="excerpt" rows="3"
                          placeholder="A short summary shown on the blog listing page (optional — auto-generated from body if blank)."><?= htmlspecialchars($post['excerpt'] ?? '') ?></textarea>
            </div>
        </div>

        <!-- ── Sidebar ── -->
        <div>
            <!-- Publish -->
            <div class="b-card">
                <h2>Publish</h2>
                <label style="font-weight:400;cursor:pointer;display:flex;align-items:center;gap:.5rem;margin-bottom:1rem;">
                    <input type="checkbox" name="published" value="1"
                           <?= !empty($post['published'])?'checked':'' ?>>
                    <span>Published (live on website)</span>
                </label>

                <label style="font-weight:600;font-size:.88rem;">Post date</label>
                <input type="date" name="posted_at"
                       value="<?= htmlspecialchars($post['posted_at'] ?? date('Y-m-d')) ?>">

                <div style="display:flex;gap:.5rem;margin-top:1rem;">
                    <button type="submit" class="btn" style="flex:1;">
                        <?= $is_add ? 'Publish post' : 'Save changes' ?>
                    </button>
                </div>
                <?php if (!$is_add): ?>
                    <a href="blog.php" class="btn btn-outline" style="width:100%;margin-top:.4rem;text-align:center;">
                        Cancel
                    </a>
                <?php endif; ?>
            </div>

            <!-- Author -->
            <div class="b-card">
                <h2>Author</h2>
                <input type="text" name="author"
                       value="<?= htmlspecialchars($post['author'] ?? '') ?>"
                       placeholder="e.g. Buy Local Team">
            </div>

            <!-- Tags -->
            <div class="b-card">
                <h2>Tags</h2>
                <input type="text" name="tags"
                       value="<?= htmlspecialchars($post['tags'] ?? '') ?>"
                       placeholder="community, events, local">
                <p class="muted" style="font-size:.78rem;margin-top:.25rem;">Comma-separated.</p>
            </div>

            <!-- Cover image -->
            <div class="b-card">
                <h2>Cover image</h2>

                <?php if (!empty($post['cover_image'])): ?>
                    <img src="../<?= htmlspecialchars($post['cover_image']) ?>"
                         alt="cover" class="cover-preview" id="cover-preview">
                    <label style="display:flex;align-items:center;gap:.4rem;font-size:.82rem;margin-bottom:.75rem;cursor:pointer;">
                        <input type="checkbox" name="remove_cover" value="1" id="remove-cover">
                        Remove current cover image
                    </label>
                <?php else: ?>
                    <img id="cover-preview" class="cover-preview" src="" style="display:none;">
                <?php endif; ?>

                <div class="upload-zone" id="cover-zone">
                    <input type="file" name="cover_image" id="cover-input"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                    <div id="cover-prompt">
                        <div style="font-size:1.5rem;">🖼</div>
                        <p style="font-size:.82rem;margin:.4rem 0 0;color:var(--ink-muted);">
                            Click or drag image (JPG/PNG, max 3MB)
                        </p>
                    </div>
                </div>
            </div>
        </div>

    </div>
</form>

</div>
</section>

<script>
// ── Body editor ──────────────────────────────────────────────
const editor   = document.getElementById('editor-content');
const bodyHide = document.getElementById('body-hidden');
const toolbar  = document.getElementById('toolbar');

// Load saved content into editor
const savedBody = <?= json_encode($post['body'] ?? '') ?>;
if (savedBody) editor.innerHTML = savedBody;

// Sync editor → hidden textarea on every input
editor.addEventListener('input', syncBody);
function syncBody() { bodyHide.value = editor.innerHTML; }
syncBody();

// Toolbar commands
toolbar.querySelectorAll('button[data-cmd]').forEach(btn => {
    btn.addEventListener('click', function (e) {
        e.preventDefault();
        editor.focus();
        const cmd = this.dataset.cmd;

        if (cmd === 'h2' || cmd === 'h3') {
            document.execCommand('formatBlock', false, cmd);
        } else if (cmd === 'blockquote') {
            document.execCommand('formatBlock', false, 'blockquote');
        } else if (cmd === 'createLink') {
            const url = prompt('Enter URL:', 'https://');
            if (url) document.execCommand('createLink', false, url);
        } else if (cmd === 'insertImage') {
            const url = prompt('Enter image URL:');
            if (url) document.execCommand('insertImage', false, url);
        } else {
            document.execCommand(cmd, false, null);
        }
        syncBody();
        updateToolbar();
    });
});

function updateToolbar() {
    toolbar.querySelectorAll('button[data-cmd]').forEach(btn => {
        const cmd = btn.dataset.cmd;
        if (['bold','italic','underline'].includes(cmd)) {
            btn.classList.toggle('active', document.queryCommandState(cmd));
        }
    });
}
editor.addEventListener('keyup', updateToolbar);
editor.addEventListener('mouseup', updateToolbar);

// Sync before form submit
document.querySelector('form').addEventListener('submit', syncBody);

// ── Auto-slug from title ─────────────────────────────────────
const titleInput = document.getElementById('post-title');
const slugInput  = document.getElementById('post-slug');

titleInput.addEventListener('input', function () {
    if (!slugInput.dataset.edited) {
        slugInput.value = this.value.toLowerCase()
            .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    }
});
slugInput.addEventListener('input', () => slugInput.dataset.edited = '1');

// ── Cover image preview ──────────────────────────────────────
const coverInput   = document.getElementById('cover-input');
const coverPreview = document.getElementById('cover-preview');
const coverPrompt  = document.getElementById('cover-prompt');
const coverZone    = document.getElementById('cover-zone');
const removeCover  = document.getElementById('remove-cover');

if (coverInput) {
    coverInput.addEventListener('change', function () {
        if (this.files && this.files[0]) {
            const r = new FileReader();
            r.onload = e => {
                coverPreview.src = e.target.result;
                coverPreview.style.display = 'block';
                coverPrompt.style.display  = 'none';
            };
            r.readAsDataURL(this.files[0]);
        }
    });
}
if (coverZone) {
    coverZone.addEventListener('dragover',  e => { e.preventDefault(); coverZone.classList.add('dragover'); });
    coverZone.addEventListener('dragleave', () => coverZone.classList.remove('dragover'));
    coverZone.addEventListener('drop', e => {
        e.preventDefault(); coverZone.classList.remove('dragover');
        if (e.dataTransfer.files[0]) {
            const dt = new DataTransfer();
            dt.items.add(e.dataTransfer.files[0]);
            coverInput.files = dt.files;
            coverInput.dispatchEvent(new Event('change'));
        }
    });
}
if (removeCover) {
    removeCover.addEventListener('change', function () {
        if (this.checked && coverPreview) {
            coverPreview.style.opacity = '.3';
        } else if (coverPreview) {
            coverPreview.style.opacity = '1';
        }
    });
}
</script>


// Actually we need _footer.php
require __DIR__ . '/_footer.php'; ?>