<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');

$success_message = '';
$error_message   = '';

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM pages WHERE id = ?");
        $stmt->execute([(int)$_POST['delete_id']]);
        $success_message = 'Page deleted successfully.';
    } catch (PDOException $e) {
        $error_message = 'Error: ' . $e->getMessage();
    }
}

// Search & Filter
$search = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';
$params = [];
$where  = [];

if ($search) {
    $where[]  = "(title LIKE ? OR slug LIKE ? OR overview LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($status && in_array($status, ['draft','published','archived'])) {
    $where[]  = "status = ?";
    $params[] = $status;
}

$sql = "SELECT * FROM pages" . ($where ? " WHERE " . implode(' AND ', $where) : "") . " ORDER BY updated_at DESC";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $pages = $stmt->fetchAll();

    // Stats
    $stats = $pdo->query("SELECT
        COUNT(*) as total,
        SUM(status='published') as published,
        SUM(status='draft') as draft,
        SUM(status='archived') as archived
        FROM pages")->fetch();
} catch (PDOException $e) {
    $error_message = 'DB Error: ' . $e->getMessage();
    $pages = [];
    $stats = ['total'=>0,'published'=>0,'draft'=>0,'archived'=>0];
}

$active_section = 'pages';
$user_name = $_SESSION['username'] ?? 'Admin';
$user_role = $_SESSION['role'] ?? 'admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pages — RSIS Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Roboto', sans-serif; margin: 0; height: 100vh; overflow: hidden; }
        body.dark { background-color: #1a202c; color: #e2e8f0; }
        .sidebar {
            width: 250px; background: #2d3748; color: white;
            transition: all 0.3s ease-in-out; height: 100%;
            position: fixed; top: 0; left: 0; z-index: 10; overflow-y: auto;
        }
        .sidebar.collapsed { width: 70px; }
        .sidebar.collapsed .sidebar-title { display: none; }
        .content { margin-left: 250px; padding: 0; transition: margin-left 0.3s; height: 100vh; overflow-y: auto; }
        .content.collapsed-sidebar { margin-left: 70px; }
        .nav-item { padding: 10px 12px; cursor: pointer; transition: background 0.2s; display: flex; align-items: center; }
        .nav-item:hover { background: #4a5568; }
        .nav-item.active { background: #4a5568; border-left: 4px solid #4299e1; }
        body.dark .bg-white { background-color: #2d3748; }
        body.dark .text-gray-700 { color: #d1d5db; }
        body.dark table { color: #e2e8f0; }
        body.dark .border-gray-200 { border-color: #4a5568; }
        body.dark .bg-gray-50 { background-color: #374151; }
        body.dark input, body.dark select { background-color: #374151; color: #e5e7eb; border-color: #4b5563; }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-250px); }
            .sidebar.mobile-open { transform: translateX(0); }
            .content { margin-left: 0; }
        }
        .status-badge { display:inline-flex; align-items:center; gap:5px; padding:3px 10px; border-radius:9999px; font-size:11px; font-weight:500; }
        .status-badge::before { content:''; width:6px; height:6px; border-radius:50%; }
        .badge-published { background:rgba(16,185,129,.12); color:#059669; }
        .badge-published::before { background:#059669; }
        .badge-draft { background:rgba(245,158,11,.12); color:#d97706; }
        .badge-draft::before { background:#d97706; }
        .badge-archived { background:rgba(107,114,128,.12); color:#6b7280; }
        .badge-archived::before { background:#6b7280; }
    </style>
</head>
<body class="bg-gray-100">

    <button onclick="toggleMobileSidebar()"
        class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

    <?php include __DIR__ . '/include/sidebar.php'; ?>

    <div class="content" id="content" style="margin-top:50px;">
        <!-- Top Header Bar -->
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
            <div class="flex items-center gap-3">
                <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block">
                    <i class="fas fa-bars text-lg"></i>
                </button>
                <div>
                    <h1 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                        <i class="fas fa-file-alt text-blue-600"></i> Pages
                    </h1>
                    <p class="text-xs text-gray-500 mt-0.5">Manage all CMS pages</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <button id="darkModeToggle" class="text-gray-500 hover:text-gray-700 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
                    <i class="fas fa-moon"></i>
                </button>
                <a href="pages_create.php"
                    class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-medium shadow transition">
                    <i class="fas fa-plus"></i> New Page
                </a>
            </div>
        </div>

        <main class="p-6">

            <!-- Flash messages -->
            <?php if ($success_message): ?>
            <div class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-5 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
            </div>
            <?php endif; ?>
            <?php if ($error_message): ?>
            <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error_message) ?>
            </div>
            <?php endif; ?>

            <!-- Stats Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
                    <div class="text-2xl font-bold text-gray-800"><?= $stats['total'] ?></div>
                    <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Total Pages</div>
                </div>
                <div class="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
                    <div class="text-2xl font-bold text-green-600"><?= $stats['published'] ?></div>
                    <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Published</div>
                </div>
                <div class="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
                    <div class="text-2xl font-bold text-yellow-500"><?= $stats['draft'] ?></div>
                    <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Drafts</div>
                </div>
                <div class="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
                    <div class="text-2xl font-bold text-gray-500"><?= $stats['archived'] ?></div>
                    <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Archived</div>
                </div>
            </div>

            <!-- Table Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-100">
                <!-- Toolbar -->
                <div class="p-4 border-b border-gray-100 flex flex-wrap gap-3 items-center">
                    <form method="GET" class="flex flex-wrap gap-3 flex-1">
                        <div class="relative flex-1 min-w-[200px] max-w-sm">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                            <input type="text" name="q" placeholder="Search pages…"
                                value="<?= htmlspecialchars($search) ?>"
                                class="w-full border border-gray-300 rounded-lg pl-9 pr-4 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        <select name="status" onchange="this.form.submit()"
                            class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Status</option>
                            <option value="published" <?= $status==='published'?'selected':'' ?>>Published</option>
                            <option value="draft"     <?= $status==='draft'    ?'selected':'' ?>>Draft</option>
                            <option value="archived"  <?= $status==='archived' ?'selected':'' ?>>Archived</option>
                        </select>
                        <?php if ($search || $status): ?>
                        <a href="pages.php" class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-1">
                            <i class="fas fa-times"></i> Clear
                        </a>
                        <?php endif; ?>
                    </form>
                    <span class="text-sm text-gray-500"><?= count($pages) ?> result<?= count($pages) !== 1 ? 's' : '' ?></span>
                </div>

                <!-- Table -->
                <div class="overflow-x-auto">
                    <?php if (empty($pages)): ?>
                    <div class="text-center py-16">
                        <i class="fas fa-file-alt text-4xl text-gray-300 mb-4 block"></i>
                        <p class="text-gray-500 font-medium">No pages found</p>
                        <p class="text-gray-400 text-sm mt-1">
                            <?= ($search || $status) ? 'Try adjusting your filters' : 'Create your first page to get started' ?>
                        </p>
                        <?php if (!$search && !$status): ?>
                        <a href="pages_create.php" class="mt-4 inline-flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-700">
                            <i class="fas fa-plus"></i> Create Page
                        </a>
                        <?php endif; ?>
                    </div>
                    <?php else: ?>
                    <table class="w-full text-sm text-left text-gray-600">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">#</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">Title</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">Slug</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">Status</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">Created At</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide">Updated At</th>
                                <th class="px-5 py-3 font-semibold text-gray-700 text-xs uppercase tracking-wide text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <?php foreach ($pages as $i => $page): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="px-5 py-3 text-gray-400 font-mono text-xs"><?= $i + 1 ?></td>
                                <td class="px-5 py-3">
                                    <div class="font-semibold text-gray-800 max-w-[180px] truncate" title="<?= htmlspecialchars($page['title']) ?>">
                                        <?= htmlspecialchars($page['title']) ?>
                                    </div>
                                    <?php if ($page['overview']): ?>
                                    <div class="text-xs text-gray-400 mt-0.5 max-w-[180px] truncate">
                                        <?= htmlspecialchars(substr($page['overview'], 0, 60)) ?>…
                                    </div>
                                    <?php endif; ?>
                                </td>
                                <td class="px-5 py-3">
                                    <code class="text-blue-600 bg-blue-50 px-2 py-0.5 rounded text-xs font-mono">/<?= htmlspecialchars($page['slug']) ?></code>
                                </td>
                                <td class="px-5 py-3">
                                    <span class="status-badge badge-<?= $page['status'] ?>"><?= ucfirst($page['status']) ?></span>
                                </td>
                                <td class="px-5 py-3 text-xs text-gray-500 font-mono whitespace-nowrap">
                                    <?= date('d M Y', strtotime($page['created_at'])) ?><br>
                                    <span class="text-gray-400"><?= date('H:i', strtotime($page['created_at'])) ?></span>
                                </td>
                                <td class="px-5 py-3 text-xs text-gray-500 font-mono whitespace-nowrap">
                                    <?= date('d M Y', strtotime($page['updated_at'])) ?><br>
                                    <span class="text-gray-400"><?= date('H:i', strtotime($page['updated_at'])) ?></span>
                                </td>
                                <td class="px-5 py-3">
                                    <div class="flex items-center justify-center gap-2">
                                        <a href="pages_edit.php?id=<?= $page['id'] ?>"
                                            class="bg-blue-50 hover:bg-blue-100 text-blue-600 px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 transition">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <form method="POST"
                                            onsubmit="return confirm('Delete \'<?= addslashes($page['title']) ?>\'? This cannot be undone.')">
                                            <input type="hidden" name="delete_id" value="<?= $page['id'] ?>">
                                            <button type="submit"
                                                class="bg-red-50 hover:bg-red-100 text-red-600 px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 transition">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        function toggleMobileSidebar() {
            document.getElementById('sidebar').classList.toggle('mobile-open');
        }
        let sidebarCollapsed = false;
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            const icon    = document.getElementById('collapseIcon');
            sidebarCollapsed = !sidebarCollapsed;
            sidebar.classList.toggle('collapsed', sidebarCollapsed);
            content.classList.toggle('collapsed-sidebar', sidebarCollapsed);
            if (icon) icon.classList.toggle('fa-chevron-left', !sidebarCollapsed),
                      icon.classList.toggle('fa-chevron-right', sidebarCollapsed);
        }
        document.getElementById('darkModeToggle').addEventListener('click', function() {
            document.body.classList.toggle('dark');
            const icon = this.querySelector('i');
            icon.classList.toggle('fa-moon');
            icon.classList.toggle('fa-sun');
            localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
        });
        if (localStorage.getItem('darkMode') === 'enabled') {
            document.body.classList.add('dark');
            document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
        }
        // Auto-submit search on enter
        document.querySelector('input[name="q"]').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') this.closest('form').submit();
        });
    </script>
</body>
</html>