<?php
$pageTitle = 'Website Pages';
require_once dirname(__DIR__) . '/includes/header.php';

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    db()->query("DELETE FROM pages WHERE id=$id");
    flash('Page deleted.', 'success');
    redirect(ADMIN_URL . '/pages/pages.php');
}

$pages = db()->query("SELECT * FROM pages ORDER BY slug ASC")->fetch_all(MYSQLI_ASSOC);
?>

<div class="page-header">
    <h1>Website Pages</h1>
    <div class="page-header-actions">
        <a href="page-add.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add Page</a>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <i class="fas fa-file-alt" style="color:var(--brand)"></i>
        <h2>All Pages</h2>
        <span style="color:var(--muted);font-size:13px;margin-left:auto"><?= count($pages) ?> pages</span>
    </div>
    <div class="table-wrap">
        <?php if (empty($pages)): ?>
        <div style="padding:48px;text-align:center;color:var(--muted)">
            <i class="fas fa-file-alt" style="font-size:36px;opacity:.3;display:block;margin-bottom:12px"></i>
            No pages yet. <a href="page-add.php" style="color:var(--brand)">Create your first page</a>
        </div>
        <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Page Title</th>
                    <th>Slug</th>
                    <th>Status</th>
                    <th>Last Updated</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($pages as $p): ?>
            <tr>
                <td style="font-weight:600"><?= e($p['title']) ?></td>
                <td style="color:var(--muted);font-size:13px">/<?= e($p['slug']) ?></td>
                <td><span class="badge <?= $p['status']==='published'?'badge-green':'badge-yellow' ?>"><?= ucfirst($p['status']) ?></span></td>
                <td style="color:var(--muted);font-size:13px"><?= date('M j, Y', strtotime($p['updated_at'])) ?></td>
                <td>
                    <div style="display:flex;gap:6px">
                        <a href="page-edit.php?id=<?= $p['id'] ?>" class="btn btn-secondary btn-sm btn-icon" title="Edit"><i class="fas fa-edit"></i></a>
                        <a href="<?= SITE_URL ?>/<?= e($p['slug']) ?>.php" target="_blank" class="btn btn-secondary btn-sm btn-icon" title="View"><i class="fas fa-eye"></i></a>
                        <button onclick="confirmDelete('pages.php?delete=<?= $p['id'] ?>','<?= e(addslashes($p['title'])) ?>')" class="btn btn-danger btn-sm btn-icon" title="Delete"><i class="fas fa-trash"></i></button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
