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

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

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

// Total survey count
$totalStmt = $dbh->query("SELECT COUNT(*) FROM surveys");
$totalSurveys = $totalStmt->fetchColumn();

// Paginated query
$stmt = $dbh->prepare("SELECT * FROM surveys ORDER BY id DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$surveys = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalPages = ceil($totalSurveys / $limit);

// 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); }

  /* ── 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; white-space: nowrap; max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
  .data-table tr:hover td { background: rgba(255,255,255,0.015); }
  .data-table tr:last-child td { border-bottom: none; }

  /* ── 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">User Feedback</div>
            <div class="ph-title">Survey <strong>List</strong></div>
        </div>
        <div>
            <a href="add_survey.php" class="btn-primary-custom">
                <i class="fas fa-plus-circle"></i> Add New Survey
            </a>
        </div>
    </div>

    <!-- Search Box -->
    <div class="search-wrapper">
        <i class="fas fa-search"></i>
        <input type="text" id="searchInput" class="search-input" placeholder="Search surveys..." autocomplete="off">
    </div>

    <!-- Table Panel -->
    <div class="panel" style="overflow-x:auto;">
        <table class="data-table" id="surveyTable">
            <thead>
                <tr>
                    <?php if (!empty($surveys)): ?>
                        <?php foreach (array_keys($surveys[0]) as $col): ?>
                            <th><?= htmlspecialchars(ucwords(str_replace('_', ' ', $col))) ?></th>
                        <?php endforeach; ?>
                        <th>Actions</th>
                    <?php else: ?>
                        <th>No surveys found</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($surveys)): ?>
                    <tr>
                        <td style="text-align: center; padding: 40px 20px; color: var(--text-3);">
                            No surveys found in the database.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($surveys as $survey): ?>
                        <tr>
                            <?php foreach ($survey as $value): ?>
                                <!-- Used a slight truncate effect if the text is too long -->
                                <td title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></td>
                            <?php endforeach; ?>
                            <td>
                                <div class="action-btns">
                                    <a href="survey_view.php?id=<?= $survey['id'] ?>" class="btn-act btn-act-view" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit_survey.php?id=<?= $survey['id'] ?>" class="btn-act btn-act-edit" title="Edit">
                                        <i class="fas fa-pencil-alt"></i>
                                    </a>
                                    <a href="survey_delete.php?id=<?= $survey['id'] ?>" class="btn-act btn-act-del" title="Delete" onclick="return confirm('Are you sure you want to delete this survey?')">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <ul class="dark-pagination">
            <!-- Prev Button -->
            <li class="<?= ($page <= 1) ? 'disabled' : '' ?>">
                <?php if ($page > 1): ?>
                    <a href="?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 ($p = 1; $p <= $totalPages; $p++): ?>
                <li class="<?= ($p == $page) ? 'active' : '' ?>">
                    <?php if ($p == $page): ?>
                        <span><?= $p ?></span>
                    <?php else: ?>
                        <a href="?page=<?= $p ?>"><?= $p ?></a>
                    <?php endif; ?>
                </li>
            <?php endfor; ?>

            <!-- Next Button -->
            <li class="<?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                <?php if ($page < $totalPages): ?>
                    <a href="?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
    document.getElementById('searchInput').addEventListener('input', function () {
        const filter = this.value.toLowerCase();
        const rows = document.querySelectorAll('#surveyTable tbody tr');
        
        rows.forEach(row => {
            // Check if this is the "no surveys found" row to prevent hiding it weirdly if it's the only row
            if(row.cells.length === 1) return; 

            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(filter) ? '' : 'none';
        });
    });
</script>

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