<?php
session_start();
require 'config.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

$limit = 10; // articles per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $limit;

$selectedCategory = trim($_GET['category'] ?? '');

// Build category list for filter dropdown
$categoryStmt = $dbh->query("SELECT DISTINCT category FROM articles WHERE category IS NOT NULL AND TRIM(category) <> '' ORDER BY category ASC");
$categories = $categoryStmt ? $categoryStmt->fetchAll(PDO::FETCH_COLUMN) : [];

// Get articles with limit and offset
$baseWhere = '';
$params = [];
if ($selectedCategory !== '') {
    $baseWhere = " WHERE TRIM(LOWER(category)) = TRIM(LOWER(:category)) ";
    $params[':category'] = $selectedCategory;
}

$stmt = $dbh->prepare("SELECT * FROM articles " . $baseWhere . " ORDER BY published_at DESC, id DESC LIMIT :limit OFFSET :offset");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value, PDO::PARAM_STR);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll();

// Count total articles
$countStmt = $dbh->prepare("SELECT COUNT(*) FROM articles " . $baseWhere);
foreach ($params as $key => $value) {
    $countStmt->bindValue($key, $value, PDO::PARAM_STR);
}
$countStmt->execute();
$totalArticles = (int)$countStmt->fetchColumn();
$totalPages = ceil($totalArticles / $limit);
if ($totalPages < 1) {
    $totalPages = 1;
}
if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $limit;

    // Re-fetch rows for corrected page number
    $stmt = $dbh->prepare("SELECT * FROM articles " . $baseWhere . " ORDER BY published_at DESC, id DESC LIMIT :limit OFFSET :offset");
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value, PDO::PARAM_STR);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $articles = $stmt->fetchAll();
}

// Include Premium Admin Header & Sidebar
include "includes/header.php";
include "includes/sidebar.php";
?>

<style>
  /* ── Layout & Page Header ── */
  .dash { max-width: 1380px; margin: 0 auto; padding: 30px 26px; z-index: 1; position: relative; }
  
  .page-header { display: flex; align-items: flex-end; justify-content: space-between; margin-bottom: 28px; flex-wrap: wrap; gap: 14px; }
  .ph-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; letter-spacing: 3.5px; text-transform: uppercase; color: var(--yellow-dim); margin-bottom: 6px; display: flex; align-items: center; gap: 7px; }
  .ph-eyebrow::before { content: ''; display: inline-block; width: 20px; height: 2px; background: var(--yellow); border-radius: 2px; }
  .ph-title { font-family: 'Syne', sans-serif; font-size: 2rem; font-weight: 800; color: var(--text-1); letter-spacing: -0.5px; line-height: 1.1; }
  
  .btn-primary-custom { background: var(--yellow); color: var(--dark-900); padding: 10px 20px; border-radius: 8px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; font-size: 0.9rem; transition: 0.2s; border: none; cursor: pointer; }
  .btn-primary-custom:hover { background: var(--yellow-bright); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(245,197,24,0.3); }

  /* ── Search Bar ── */
  .search-wrapper { position: relative; max-width: 400px; margin-bottom: 20px; }
  .search-wrapper i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: var(--text-3); font-size: 0.9rem; }
  .search-input { width: 100%; padding: 12px 15px 12px 40px; background: var(--dark-700); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; color: var(--text-1); font-size: 0.9rem; transition: 0.3s; }
  .search-input:focus { outline: none; border-color: var(--yellow); box-shadow: 0 0 0 3px var(--yellow-glass); }

    .filter-row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 14px; }
    .filter-select { min-width: 220px; padding: 11px 12px; background: var(--dark-700); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; color: var(--text-1); font-size: 0.9rem; }
    .filter-meta { font-size: 0.82rem; color: var(--text-2); }

  /* ── Data Table Panel ── */
  .panel { background: var(--dark-700); border: 1px solid rgba(255,255,255,0.05); border-radius: 14px; overflow: hidden; }
  .data-table { width: 100%; border-collapse: collapse; }
  .data-table th { font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; text-transform: uppercase; color: var(--text-3); padding: 16px 18px; border-bottom: 1px solid rgba(255,255,255,0.04); text-align: left; background: var(--dark-600); white-space: nowrap; }
  .data-table td { padding: 14px 18px; font-size: 0.85rem; color: var(--text-1); border-bottom: 1px solid rgba(255,255,255,0.03); vertical-align: middle; }
  .data-table tr:hover td { background: rgba(255,255,255,0.015); }
  .data-table tr:last-child td { border-bottom: none; }

  /* ── Table Typography & Badges ── */
  .td-id { font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; color: var(--text-3); }
  .td-title { font-weight: 600; color: var(--text-1); }
  .td-category { background: rgba(255,255,255,0.05); color: var(--text-2); padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; border: 1px solid rgba(255,255,255,0.03); }
  .td-date { font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; color: var(--text-3); }

  /* ── Action Buttons ── */
  .action-btns { display: flex; gap: 8px; }
  .btn-act { width: 32px; height: 32px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 0.85rem; border: none; cursor: pointer; transition: 0.2s; text-decoration: none; }
  .btn-act-view { background: rgba(76,168,245,0.1); color: var(--blue); border: 1px solid rgba(76,168,245,0.2); }
  .btn-act-view:hover { background: var(--blue); color: #fff; box-shadow: 0 4px 10px rgba(76,168,245,0.3); }
  .btn-act-edit { background: rgba(245,160,32,0.1); color: var(--orange); border: 1px solid rgba(245,160,32,0.2); }
  .btn-act-edit:hover { background: var(--orange); color: #fff; box-shadow: 0 4px 10px rgba(245,160,32,0.3); }
  .btn-act-del { background: rgba(239,79,74,0.1); color: var(--red); border: 1px solid rgba(239,79,74,0.2); }
  .btn-act-del:hover { background: var(--red); color: #fff; box-shadow: 0 4px 10px rgba(239,79,74,0.3); }

  /* ── Dark Pagination ── */
  .dark-pagination { display: flex; justify-content: center; gap: 8px; margin-top: 30px; list-style: none; padding: 0; }
  .dark-pagination a, .dark-pagination span {
      display: flex; align-items: center; justify-content: center; width: 36px; height: 36px;
      border-radius: 8px; background: var(--dark-700); color: var(--text-2); border: 1px solid rgba(255,255,255,0.05);
      text-decoration: none; font-family: 'JetBrains Mono', monospace; font-size: 0.85rem; transition: 0.2s; cursor: pointer;
  }
  .dark-pagination a:hover { background: var(--dark-600); color: var(--yellow); border-color: var(--yellow-border); }
  .dark-pagination .active span { background: var(--yellow-glass); color: var(--yellow); border-color: var(--yellow-border); font-weight: bold; }
  .dark-pagination .disabled span { opacity: 0.3; pointer-events: none; }
</style>

<main class="dash">

    <!-- Page Header -->
    <div class="page-header">
        <div>
            <div class="ph-eyebrow">Content</div>
            <div class="ph-title">Articles <strong>List</strong></div>
        </div>
        <div>
            <a href="article_create.php" class="btn-primary-custom">
                <i class="fas fa-plus-circle"></i> Add New Article
            </a>
        </div>
    </div>

    <!-- Filter + Search -->
    <form method="get" class="filter-row">
        <select name="category" class="filter-select" onchange="this.form.submit()">
            <option value="">All Categories</option>
            <?php foreach ($categories as $cat): ?>
                <option value="<?= htmlspecialchars($cat) ?>" <?= (strcasecmp(trim($cat), trim($selectedCategory)) === 0) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php if ($selectedCategory !== ''): ?>
            <a href="articles_list.php" class="btn-cancel" style="padding: 9px 14px;">Clear Filter</a>
        <?php endif; ?>
        <span class="filter-meta">
            Total <?= htmlspecialchars($selectedCategory !== '' ? $selectedCategory : 'Articles') ?>: <strong><?= $totalArticles ?></strong>
        </span>
    </form>

    <div class="search-wrapper">
        <i class="fas fa-search"></i>
        <input type="text" id="searchInput" class="search-input" placeholder="Search current page...">
    </div>

    <!-- Table Panel -->
    <div class="panel" style="overflow-x:auto;">
        <table class="data-table" id="articlesTable">
            <thead>
                <tr>
                    <th>S.No</th>
                    <th>Title</th>
                    <th>Category</th>
                    <th>Published At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($articles): ?>
                    <?php $serial = $offset + 1; ?>
                    <?php foreach ($articles as $a): ?>
                        <tr>
                            <td><span class="td-id"><?= $serial++ ?></span></td>
                            <td class="td-title"><?= htmlspecialchars($a['title']) ?></td>
                            <td><span class="td-category"><?= htmlspecialchars($a['category']) ?></span></td>
                            <td><span class="td-date"><i class="far fa-calendar-alt" style="color: var(--text-3); margin-right: 5px;"></i> <?= htmlspecialchars(date('d M Y', strtotime($a['published_at']))) ?></span></td>
                            <td>
                                <div class="action-btns">
                                    <a href="article_view.php?id=<?= $a['id'] ?>" class="btn-act btn-act-view" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="article_edit.php?id=<?= $a['id'] ?>" class="btn-act btn-act-edit" title="Edit">
                                        <i class="fas fa-pencil-alt"></i>
                                    </a>
                                    <a href="article_delete.php?id=<?= $a['id'] ?>" class="btn-act btn-act-del" title="Delete" onclick="return confirm('Are you sure you want to delete this article?');">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px 20px; color: var(--text-3);">No articles found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <?php
            $baseParams = [];
            if ($selectedCategory !== '') {
                $baseParams['category'] = $selectedCategory;
            }
        ?>
        <ul class="dark-pagination">
            <!-- Prev Button -->
            <li class="<?= ($page <= 1) ? 'disabled' : '' ?>">
                <?php if ($page > 1): ?>
                    <a href="?<?= htmlspecialchars(http_build_query(array_merge($baseParams, ['page' => $page - 1]))) ?>"><i class="fas fa-chevron-left"></i></a>
                <?php else: ?>
                    <span><i class="fas fa-chevron-left"></i></span>
                <?php endif; ?>
            </li>

            <!-- Page Numbers -->
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="<?= ($i === $page) ? 'active' : '' ?>">
                    <?php if ($i === $page): ?>
                        <span><?= $i ?></span>
                    <?php else: ?>
                        <a href="?<?= htmlspecialchars(http_build_query(array_merge($baseParams, ['page' => $i]))) ?>"><?= $i ?></a>
                    <?php endif; ?>
                </li>
            <?php endfor; ?>

            <!-- Next Button -->
            <li class="<?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                <?php if ($page < $totalPages): ?>
                    <a href="?<?= htmlspecialchars(http_build_query(array_merge($baseParams, ['page' => $page + 1]))) ?>"><i class="fas fa-chevron-right"></i></a>
                <?php else: ?>
                    <span><i class="fas fa-chevron-right"></i></span>
                <?php endif; ?>
            </li>
        </ul>
    <?php endif; ?>

</main>

<script>
// Live Search Filtering
document.getElementById('searchInput').addEventListener('keyup', function () {
    let filter = this.value.toLowerCase();
    let rows = document.querySelectorAll('#articlesTable tbody tr');
    
    rows.forEach(row => {
        // Skip the "No articles found" row
        if (row.cells.length === 1) return;
        
        const text = row.innerText.toLowerCase();
        row.style.display = text.includes(filter) ? '' : 'none';
    });
});
</script>

<?php include "includes/footer.php"; ?>