<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';

$search = trim($_GET['search'] ?? '');
$status = trim($_GET['status'] ?? '');
$type = trim($_GET['type'] ?? '');

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max($page, 1);

$perPage = 12;
$offset = ($page - 1) * $perPage;

$allowedStatuses = ['draft', 'pending', 'published'];
$allowedTypes = ['news', 'article', 'guide', 'blog', 'tickets'];

if (!in_array($status, $allowedStatuses, true)) {
    $status = '';
}

if (!in_array($type, $allowedTypes, true)) {
    $type = '';
}

$whereParts = [];
$params = [];

if ($search !== '') {
    $whereParts[] = "(
        p.title LIKE ?
        OR p.tagline LIKE ?
        OR p.slug LIKE ?
        OR p.tags LIKE ?
        OR p.post_location LIKE ?
    )";

    $searchTerm = '%' . $search . '%';

    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($status !== '') {
    $whereParts[] = "p.status = ?";
    $params[] = $status;
}

if ($type !== '') {
    $whereParts[] = "p.post_location = ?";
    $params[] = $type;
}

$whereSql = '';

if (!empty($whereParts)) {
    $whereSql = 'WHERE ' . implode(' AND ', $whereParts);
}

function buildPostsUrl(array $overrides = []): string
{
    $query = array_merge($_GET, $overrides);

    foreach ($query as $key => $value) {
        if ($value === '' || $value === null) {
            unset($query[$key]);
        }
    }

    return '/admin/posts' . (!empty($query) ? '?' . http_build_query($query) : '');
}

function formatPostType(?string $type): string
{
    if (!$type) {
        return 'Unknown';
    }

    return ucwords(str_replace(['-', '_'], ' ', $type));
}

function getStatusBadgeClass(?string $status): string
{
    return match ($status) {
        'draft' => 'post-status-draft',
        'pending' => 'post-status-pending',
        'published' => 'post-status-published',
        default => 'post-status-unknown',
    };
}

try {
    $countStmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM posts p
        $whereSql
    ");

    $countStmt->execute($params);
    $totalPosts = (int)$countStmt->fetchColumn();

    $totalPages = max((int)ceil($totalPosts / $perPage), 1);

    if ($page > $totalPages) {
        $page = $totalPages;
        $offset = ($page - 1) * $perPage;
    }

    $postsStmt = $pdo->prepare("
        SELECT 
            p.id,
            p.title,
            p.tags,
            p.slug,
            p.tagline,
            p.post_location,
            p.featured,
            p.status,
            p.created_at
        FROM posts p
        $whereSql
        ORDER BY p.created_at DESC
        LIMIT $perPage OFFSET $offset
    ");

    $postsStmt->execute($params);
    $posts = $postsStmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die('Database error: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'));
}

$showingFrom = $totalPosts > 0 ? $offset + 1 : 0;
$showingTo = min($offset + $perPage, $totalPosts);
?>

<link rel="stylesheet" href="/admin/css/posts.css">

<div class="posts-page">

    <div class="posts-hero">
        <div>

            <h1>
                All Posts
            </h1>

            <p class="posts-hero-text">
                Search, filter and manage ThrillSense content from one place.
            </p>
        </div>

        <a href="/admin/create-post" class="btn btn-dark posts-create-button">
            Create Post
        </a>
    </div>

    <form method="get" class="posts-filter-card">

        <div class="posts-filter-main">
            <label for="search" class="form-label">
                Search posts
            </label>

            <input
                type="text"
                id="search"
                name="search"
                class="form-control"
                placeholder="Search by title, slug, tagline, tags or type..."
                value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>"
            >
        </div>

        <div class="posts-filter-select">
            <label for="status" class="form-label">
                Status
            </label>

            <select id="status" name="status" class="form-select">
                <option value="">All statuses</option>
                <option value="draft" <?= $status === 'draft' ? 'selected' : '' ?>>Draft</option>
                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="published" <?= $status === 'published' ? 'selected' : '' ?>>Published</option>
            </select>
        </div>

        <div class="posts-filter-select">
            <label for="type" class="form-label">
                Type
            </label>

            <select id="type" name="type" class="form-select">
                <option value="">All types</option>
                <option value="news" <?= $type === 'news' ? 'selected' : '' ?>>News</option>
                <option value="article" <?= $type === 'article' ? 'selected' : '' ?>>Article</option>
                <option value="guide" <?= $type === 'guide' ? 'selected' : '' ?>>Guide</option>
                <option value="blog" <?= $type === 'blog' ? 'selected' : '' ?>>Blog</option>
                <option value="tickets" <?= $type === 'tickets' ? 'selected' : '' ?>>Tickets</option>
            </select>
        </div>

        <div class="posts-filter-actions">
            <button type="submit" class="btn btn-dark">
                Search
            </button>

            <?php if ($search !== '' || $status !== '' || $type !== ''): ?>
                <a href="/admin/posts" class="btn btn-outline-secondary">
                    Clear
                </a>
            <?php endif; ?>
        </div>

    </form>

    <div class="posts-results-bar">
        <div>
            <strong><?= (int)$totalPosts ?></strong>
            <?= $totalPosts === 1 ? 'post found' : 'posts found' ?>

            <?php if ($totalPosts > 0): ?>
                <span class="text-muted">
                    - showing <?= (int)$showingFrom ?> to <?= (int)$showingTo ?>
                </span>
            <?php endif; ?>
        </div>

        <?php if ($search !== '' || $status !== '' || $type !== ''): ?>
            <div class="posts-active-filters">
                <?php if ($search !== ''): ?>
                    <span>
                        Search: <?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>
                    </span>
                <?php endif; ?>

                <?php if ($status !== ''): ?>
                    <span>
                        Status: <?= htmlspecialchars(ucfirst($status), ENT_QUOTES, 'UTF-8') ?>
                    </span>
                <?php endif; ?>

                <?php if ($type !== ''): ?>
                    <span>
                        Type: <?= htmlspecialchars(formatPostType($type), ENT_QUOTES, 'UTF-8') ?>
                    </span>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <?php if (empty($posts)): ?>

        <div class="posts-empty">
            <h2>
                No posts found
            </h2>

            <p>
                <?= $search !== '' || $status !== '' || $type !== ''
                    ? 'Try adjusting your search or filters.'
                    : 'Create your first Newsdesk post to get started.'
                ?>
            </p>

            <a href="/admin/create-post" class="btn btn-dark">
                Create Post
            </a>
        </div>

    <?php else: ?>

        <div class="posts-table-shell">

            <div class="posts-table-header">
                <div>Post</div>
                <div>Type</div>
                <div>Status</div>
                <div>Created</div>
                <div>Actions</div>
            </div>

            <div class="posts-table-body">

                <?php foreach ($posts as $post): ?>

                    <?php
                        $postType = $post['post_location'] ?? '';
                        $postStatus = $post['status'] ?? 'unknown';
                        $postUrl = '';

                        if (!empty($post['slug'])) {
                            $postUrl = '/' . (!empty($postType) ? urlencode($postType) . '/' : '') . urlencode($post['slug']);
                        }

                        $tagList = [];

                        if (!empty($post['tags'])) {
                            $tagList = array_filter(array_map('trim', explode(',', $post['tags'])));
                        }
                    ?>

                    <div class="posts-table-row">

                        <div class="posts-table-post">
                            <div class="posts-table-title-row">
                                <a
                                    href="/admin/edit-post.php?id=<?= (int)$post['id'] ?>"
                                    class="posts-table-title"
                                >
                                    <?= !empty($post['title'])
                                        ? htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8')
                                        : 'Untitled post'
                                    ?>
                                </a>

                                <?php if (!empty($post['featured'])): ?>
                                    <span class="post-featured-pill">
                                        Featured
                                    </span>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($post['tagline'])): ?>
                                <p class="posts-table-tagline">
                                    <?= htmlspecialchars($post['tagline'], ENT_QUOTES, 'UTF-8') ?>
                                </p>
                            <?php endif; ?>

                            <div class="posts-table-meta">
                                <?php if (!empty($post['slug'])): ?>
                                    <span>
                                        /<?= htmlspecialchars($post['slug'], ENT_QUOTES, 'UTF-8') ?>
                                    </span>
                                <?php endif; ?>

                                <?php if (!empty($tagList)): ?>
                                    <span>
                                        <?= htmlspecialchars(implode(', ', array_slice($tagList, 0, 4)), ENT_QUOTES, 'UTF-8') ?>
                                        <?= count($tagList) > 4 ? ' +' . (count($tagList) - 4) : '' ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="posts-table-type">
                            <span class="post-type-pill">
                                <?= htmlspecialchars(formatPostType($postType), ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        </div>

                        <div class="posts-table-status">
                            <span class="post-status-pill <?= htmlspecialchars(getStatusBadgeClass($postStatus), ENT_QUOTES, 'UTF-8') ?>">
                                <?= htmlspecialchars(ucfirst($postStatus), ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        </div>

                        <div class="posts-table-date">
                            <?= !empty($post['created_at'])
                                ? htmlspecialchars(date('d M Y', strtotime($post['created_at'])), ENT_QUOTES, 'UTF-8')
                                : 'Unknown'
                            ?>
                        </div>

                        <div class="posts-table-actions">
                            <a
                                href="/admin/edit-post.php?id=<?= (int)$post['id'] ?>"
                                class="btn btn-sm btn-dark"
                            >
                                Edit
                            </a>

                            <?php if ($postUrl): ?>
                                <a
                                    href="<?= htmlspecialchars($postUrl, ENT_QUOTES, 'UTF-8') ?>"
                                    class="btn btn-sm btn-outline-secondary"
                                    target="_blank"
                                    rel="noopener"
                                >
                                    View
                                </a>
                            <?php endif; ?>
                        </div>

                    </div>

                <?php endforeach; ?>

            </div>

        </div>

        <?php if ($totalPages > 1): ?>
            <nav class="posts-pagination" aria-label="Posts pagination">

                <a
                    class="posts-page-link <?= $page <= 1 ? 'is-disabled' : '' ?>"
                    href="<?= $page <= 1 ? '#' : htmlspecialchars(buildPostsUrl(['page' => $page - 1]), ENT_QUOTES, 'UTF-8') ?>"
                >
                    Previous
                </a>

                <div class="posts-page-numbers">
                    <?php
                        $startPage = max(1, $page - 2);
                        $endPage = min($totalPages, $page + 2);
                    ?>

                    <?php if ($startPage > 1): ?>
                        <a href="<?= htmlspecialchars(buildPostsUrl(['page' => 1]), ENT_QUOTES, 'UTF-8') ?>">
                            1
                        </a>

                        <?php if ($startPage > 2): ?>
                            <span>...</span>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a
                            href="<?= htmlspecialchars(buildPostsUrl(['page' => $i]), ENT_QUOTES, 'UTF-8') ?>"
                            class="<?= $i === $page ? 'is-active' : '' ?>"
                        >
                            <?= (int)$i ?>
                        </a>
                    <?php endfor; ?>

                    <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                            <span>...</span>
                        <?php endif; ?>

                        <a href="<?= htmlspecialchars(buildPostsUrl(['page' => $totalPages]), ENT_QUOTES, 'UTF-8') ?>">
                            <?= (int)$totalPages ?>
                        </a>
                    <?php endif; ?>
                </div>

                <a
                    class="posts-page-link <?= $page >= $totalPages ? 'is-disabled' : '' ?>"
                    href="<?= $page >= $totalPages ? '#' : htmlspecialchars(buildPostsUrl(['page' => $page + 1]), ENT_QUOTES, 'UTF-8') ?>"
                >
                    Next
                </a>

            </nav>
        <?php endif; ?>

    <?php endif; ?>

</div>

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