<?php
$page_title = 'Blog Posts';
require __DIR__ . '/_guard.php';

// Quick actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['post_id'] ?? 0);

    if ($do === 'toggle' && $id) {
        $cur = (int)db_value('SELECT published FROM blog_posts WHERE id=:id', ['id'=>$id]);
        db_exec('UPDATE blog_posts SET published=:p WHERE id=:id', ['p'=>$cur?0:1,'id'=>$id]);
    }
    if ($do === 'delete' && $id) {
        // Delete cover image file if exists
        $img = db_value('SELECT cover_image FROM blog_posts WHERE id=:id', ['id'=>$id]);
        if ($img) {
            $path = __DIR__ . '/../' . ltrim($img, '/');
            if (file_exists($path)) @unlink($path);
        }
        db_exec('DELETE FROM blog_posts WHERE id=:id', ['id'=>$id]);
        header('Location: blog.php?msg=deleted'); exit;
    }
    header('Location: blog.php'); exit;
}

$q      = trim($_GET['q'] ?? '');
$filter = $_GET['filter'] ?? 'all';

$where  = ['1=1'];
$params = [];
if ($filter === 'published')   $where[] = "published=1";
if ($filter === 'draft')       $where[] = "published=0";
if ($q !== '') {
    $where[] = "(title LIKE :q1 OR excerpt LIKE :q2 OR author LIKE :q3)";
    $params['q1'] = '%'.$q.'%';
    $params['q2'] = '%'.$q.'%';
    $params['q3'] = '%'.$q.'%';
}

$posts = db_all(
    'SELECT id, slug, title, excerpt, published, author, posted_at, cover_image, tags,
            created_at, updated_at
       FROM blog_posts WHERE '.implode(' AND ',$where).'
       ORDER BY posted_at DESC, created_at DESC LIMIT 200',
    $params
);

$counts = [
    'all'       => (int)db_value('SELECT COUNT(*) FROM blog_posts'),
    'published' => (int)db_value('SELECT COUNT(*) FROM blog_posts WHERE published=1'),
    'draft'     => (int)db_value('SELECT COUNT(*) FROM blog_posts WHERE published=0'),
];
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem 1.1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);white-space:nowrap;text-align:left;}
.atbl td{padding:.65rem 1.1rem;border-bottom:1px solid var(--line);vertical-align:middle;}
.atbl tr:last-child td{border-bottom:none;}
.atbl tbody tr:hover td{background:#fafafa;}
.ftab{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .85rem;border-radius:999px;font-size:.82rem;border:1px solid var(--line);text-decoration:none;color:var(--ink);}
.ftab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.ftab .cnt{background:rgba(0,0,0,.12);border-radius:999px;padding:.05em .45em;font-size:.78em;font-weight:700;}
.post-cover{width:52px;height:38px;object-fit:cover;border-radius:3px;border:1px solid var(--line);}
.post-cover-placeholder{width:52px;height:38px;background:var(--surface-alt);border-radius:3px;border:1px solid var(--line);display:inline-block;}
</style>

<section class="section">
<div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.25rem;">
    <h1 style="margin:0;">Blog Posts</h1>
    <a href="blog-edit.php?action=add" class="btn">+ New post</a>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide>
        <?= $_GET['msg']==='deleted' ? 'Post deleted.' : htmlspecialchars($_GET['msg']) ?>
    </div>
<?php endif; ?>

<!-- Filter + search -->
<div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap;margin-bottom:1.1rem;">
    <a href="?filter=all"       class="ftab <?= $filter==='all'?'on':'' ?>">All <span class="cnt"><?= $counts['all'] ?></span></a>
    <a href="?filter=published" class="ftab <?= $filter==='published'?'on':'' ?>">Published <span class="cnt"><?= $counts['published'] ?></span></a>
    <a href="?filter=draft"     class="ftab <?= $filter==='draft'?'on':'' ?>">Drafts <span class="cnt"><?= $counts['draft'] ?></span></a>

    <form method="get" style="display:flex;gap:.4rem;margin-left:auto;">
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
        <input type="search" name="q" value="<?= htmlspecialchars($q) ?>"
               placeholder="Search posts…" style="width:220px;">
        <button type="submit" class="btn btn-outline">Search</button>
        <?php if ($q): ?><a href="?filter=<?= htmlspecialchars($filter) ?>" class="btn btn-outline">✕</a><?php endif; ?>
    </form>
</div>

<?php if (empty($posts)): ?>
    <div class="card" style="text-align:center;padding:3rem;">
        <p style="font-size:2rem;margin:0 0 .5rem;">📝</p>
        <p class="muted">No posts yet. <a href="blog-edit.php?action=add">Write your first post →</a></p>
    </div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th style="width:60px;">Cover</th>
                <th>Title</th>
                <th>Author</th>
                <th>Date</th>
                <th>Tags</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($posts as $p): ?>
            <tr>
                <td>
                    <?php if ($p['cover_image']): ?>
                        <img src="../<?= htmlspecialchars($p['cover_image']) ?>"
                             alt="" class="post-cover">
                    <?php else: ?>
                        <span class="post-cover-placeholder"></span>
                    <?php endif; ?>
                </td>
                <td>
                    <strong><?= htmlspecialchars($p['title']) ?></strong>
                    <?php if ($p['excerpt']): ?>
                        <br><small class="muted" style="font-size:.78rem;">
                            <?= htmlspecialchars(mb_substr($p['excerpt'], 0, 80)) ?>…
                        </small>
                    <?php endif; ?>
                </td>
                <td class="muted" style="white-space:nowrap;">
                    <?= $p['author'] ? htmlspecialchars($p['author']) : '—' ?>
                </td>
                <td class="muted" style="white-space:nowrap;">
                    <?= date('j M Y', strtotime($p['posted_at'])) ?>
                </td>
                <td style="font-size:.78rem;color:var(--ink-muted);">
                    <?php if ($p['tags']): ?>
                        <?php foreach (array_slice(explode(',', $p['tags']), 0, 3) as $tag): ?>
                            <span style="background:var(--surface-alt);border-radius:3px;padding:.1em .4em;margin:.1em;display:inline-block;">
                                <?= htmlspecialchars(trim($tag)) ?>
                            </span>
                        <?php endforeach; ?>
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td>
                    <span class="tag <?= $p['published']?'tag-ok':'muted' ?>">
                        <?= $p['published'] ? 'Published' : 'Draft' ?>
                    </span>
                </td>
                <td style="white-space:nowrap;">
                    <a href="blog-edit.php?id=<?= $p['id'] ?>">Edit</a>
                    &nbsp;·&nbsp;
                    <a href="../blog-post.php?id=<?= $p['id'] ?>" target="_blank">View</a>
                    &nbsp;·&nbsp;
                    <form method="post" style="display:inline;">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="toggle">
                        <input type="hidden" name="post_id" value="<?= $p['id'] ?>">
                        <button style="background:none;border:none;cursor:pointer;color:var(--brand-primary);font-size:.875rem;padding:0;">
                            <?= $p['published'] ? 'Unpublish' : 'Publish' ?>
                        </button>
                    </form>
                    &nbsp;·&nbsp;
                    <form method="post" style="display:inline;"
                          onsubmit="return confirm('Delete this post permanently?');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="delete">
                        <input type="hidden" name="post_id" value="<?= $p['id'] ?>">
                        <button style="background:none;border:none;cursor:pointer;color:#b91c1c;font-size:.875rem;padding:0;">
                            Delete
                        </button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<p class="muted" style="font-size:.8rem;margin:.5rem 0 0;"><?= count($posts) ?> post<?= count($posts)===1?'':'s' ?>.</p>
<?php endif; ?>

</div>
</section>
<?php require __DIR__ . '/_footer.php'; ?>