<?php
/**
 * Content Builder — posts list (filtered by ?type=).
 */
require_once dirname(__DIR__, 3) . '/config.php';

Auth::require();
Auth::requirePerm('content.view');

$type = $_GET['type'] ?? 'page';
$pt   = PostType::get($type);
if (!$pt) { http_response_code(404); $pt = ['slug'=>'page','label'=>'Pages','singular'=>'Page']; $type = 'page'; }

$status = in_array($_GET['status'] ?? 'any', ['any','draft','published','trash'], true)
          ? ($_GET['status'] ?? 'any') : 'any';

$pageTitle  = $pt['label'];
$currentNav = 'content-' . $type;

// ── Handle trash / delete actions ────────────────────────────
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type'=>'error','msg'=>'Security check failed.'];
    } else {
        $id  = (int)($_POST['id'] ?? 0);
        $act = $_POST['action'] ?? '';
        if ($act === 'trash' && Auth::can('content.delete')) {
            ContentBuilderAPI::trash($id);
            $flash = ['type'=>'success','msg'=>'Moved to trash.'];
        } elseif ($act === 'delete' && Auth::can('content.delete')) {
            ContentBuilderAPI::deletePost($id);
            $flash = ['type'=>'success','msg'=>'Deleted permanently.'];
        } elseif ($act === 'publish' && Auth::can('content.publish')) {
            ContentBuilderAPI::publish($id);
            $flash = ['type'=>'success','msg'=>'Published.'];
        }
    }
}

$posts = ContentBuilderAPI::listPosts($type, ['status'=>$status, 'limit'=>100, 'orderby'=>'created_at']);

require SLATE_ROOT . '/admin/partials/header.php';
?>

<?php slate_breadcrumbs([
    ['label' => 'Dashboard', 'href' => SLATE_URL . '/admin/'],
    ['label' => $pt['label']],
]); ?>

<div class="page-header">
    <div>
        <h1><?= e($pt['label']) ?></h1>
        <p class="page-header-sub">Manage your <?= e(strtolower($pt['label'])) ?>.</p>
    </div>
    <?php if (Auth::can('content.edit')): ?>
        <a href="post-edit.php?type=<?= e(urlencode($type)) ?>" class="btn btn-primary">
            Add new <?= e($pt['singular']) ?>
        </a>
    <?php endif; ?>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>" role="status"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2>All <?= e($pt['label']) ?></h2>
        <span class="text-muted text-sm"><?= count($posts) ?> shown</span>
    </div>

    <div class="filter-chips mb-2">
        <?php foreach (['any'=>'All','published'=>'Published','draft'=>'Drafts','trash'=>'Trash'] as $k=>$lbl): ?>
            <a class="chip <?= $status===$k ? 'chip-active' : '' ?>"
               href="?type=<?= e(urlencode($type)) ?>&status=<?= e($k) ?>"><?= e($lbl) ?></a>
        <?php endforeach; ?>
    </div>

    <?php if (!$posts): ?>
        <div class="empty">
            <div class="empty-title">No <?= e(strtolower($pt['label'])) ?> yet</div>
            <p>Create one to get started.</p>
        </div>
    <?php else: ?>
        <div class="cb-list">
            <?php foreach ($posts as $p):
                $st = $p['status'];
                $dot = $st==='published' ? 'ok' : ($st==='trash' ? 'bad' : 'warn'); ?>
                <div class="cb-list-row">
                    <span class="cb-status-dot cb-dot-<?= $dot ?>" title="<?= e(ucfirst($st)) ?>"></span>
                    <div class="cb-list-main">
                        <a class="cb-list-title" href="post-edit.php?id=<?= (int)$p['id'] ?>"><?= e($p['title'] ?: '(untitled)') ?></a>
                        <div class="cb-list-meta">
                            <span class="cb-slug-pill">/<?= e($p['slug']) ?></span>
                            <span class="cb-meta-sep">·</span>
                            <span><?= e(ucfirst($st)) ?></span>
                            <span class="cb-meta-sep">·</span>
                            <span>updated <?= e(date('M j, Y', strtotime($p['updated_at']))) ?></span>
                        </div>
                    </div>
                    <div class="cb-list-actions">
                        <a class="cb-act" href="post-edit.php?id=<?= (int)$p['id'] ?>" title="Edit">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><path d="M12 20h9M16.5 3.5a2.12 2.12 0 013 3L7 19l-4 1 1-4z"/></svg>
                        </a>
                        <?php if ($st==='published'): ?>
                            <a class="cb-act" target="_blank" href="<?= e(ContentBuilderAPI::publicUrl($type, $p['slug'])) ?>" title="View">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                            </a>
                        <?php endif; ?>
                        <?php if ($st !== 'published' && Auth::can('content.publish')): ?>
                            <form method="post" style="display:inline">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="publish">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button class="cb-act cb-act-go" title="Publish">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/></svg>
                                </button>
                            </form>
                        <?php endif; ?>
                        <?php if ($st !== 'trash' && Auth::can('content.delete')): ?>
                            <form method="post" style="display:inline" onsubmit="return confirm('Move to trash?')">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="trash">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button class="cb-act cb-act-danger" title="Trash">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
                                </button>
                            </form>
                        <?php elseif ($st === 'trash' && Auth::can('content.delete')): ?>
                            <form method="post" style="display:inline" onsubmit="return confirm('Delete permanently?')">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button class="cb-act cb-act-danger" title="Delete permanently">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
