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

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

// Delete functionality
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $dbh->prepare("DELETE FROM protection_reports WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: admin_reports.php');
    exit;
}

// Fetch all reports
$stmt = $dbh->query("SELECT * FROM protection_reports ORDER BY report_date DESC");
$reports = $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); }

  /* ── 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; }

  /* ── Typography & Badges ── */
  .td-id { font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; color: var(--text-3); }
  .td-title { color: var(--text-2); font-size: 0.8rem; }
  .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-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; }
</style>

<main class="dash">

    <!-- Page Header -->
    <div class="page-header">
        <div>
            <div class="ph-eyebrow">Reports</div>
            <div class="ph-title">Protection <strong>Reports</strong></div>
        </div>
        <div>
            <a href="admin_report_add.php" class="btn-primary-custom">
                <i class="fas fa-plus-circle"></i> Add Report
            </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 reports by broker or title...">
    </div>

    <!-- Table Panel -->
    <div class="panel" style="overflow-x:auto;">
        <table id="reportsTable" class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Broker Name</th>
                    <th>Title</th>
                    <th>Report Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if(empty($reports)): ?>
                <tr><td colspan="5" style="text-align: center; padding: 40px 20px; color: var(--text-3);">No protection reports found.</td></tr>
            <?php else: ?>
                <?php foreach ($reports as $report): ?>
                    <tr>
                        <td><span class="td-id">#<?= htmlspecialchars($report['id']) ?></span></td>
                        <td><strong><?= htmlspecialchars($report['broker_name']) ?></strong></td>
                        <td class="td-title"><?= htmlspecialchars($report['title']) ?></td>
                        <td><span class="td-date"><i class="far fa-calendar-alt" style="margin-right: 5px;"></i> <?= htmlspecialchars(date('d M Y', strtotime($report['report_date']))) ?></span></td>
                        <td>
                            <div class="action-btns">
                                <a href="admin_report_edit.php?id=<?= $report['id'] ?>" class="btn-act btn-act-edit" title="Edit">
                                    <i class="fas fa-pencil-alt"></i>
                                </a>
                                <a href="admin_reports.php?delete=<?= $report['id'] ?>" onclick="return confirm('Are you sure you want to delete this report?')" class="btn-act btn-act-del" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination controls -->
    <nav>
        <ul class="dark-pagination" id="pagination"></ul>
    </nav>

</main>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const rowsPerPage = 10;
    const table = document.getElementById('reportsTable');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const searchInput = document.getElementById('searchInput');
    const pagination = document.getElementById('pagination');
    
    // Filter out "No records found" row if it exists
    let actualRows = rows.filter(row => row.cells.length > 1);
    let filteredRows = actualRows.slice();
    let currentPage = 1;

    if(actualRows.length === 0) return; // Exit if table is empty

    function displayRows(page = 1) {
        tbody.innerHTML = '';
        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;
        const rowsToDisplay = filteredRows.slice(start, end);

        rowsToDisplay.forEach(row => tbody.appendChild(row));
        currentPage = page;
        updatePagination();
    }

    function updatePagination() {
        pagination.innerHTML = '';
        const pageCount = Math.ceil(filteredRows.length / rowsPerPage);
        
        if (pageCount <= 1) return;

        for (let i = 1; i <= pageCount; i++) {
            const li = document.createElement('li');
            
            if (i === currentPage) {
                li.classList.add('active');
                const span = document.createElement('span');
                span.textContent = i;
                li.appendChild(span);
            } else {
                const a = document.createElement('a');
                a.textContent = i;
                a.addEventListener('click', function (e) {
                    e.preventDefault();
                    displayRows(i);
                });
                li.appendChild(a);
            }
            pagination.appendChild(li);
        }
    }

    function filterRows() {
        const query = searchInput.value.toLowerCase().trim();

        filteredRows = actualRows.filter(row => {
            return Array.from(row.cells).some(td =>
                td.textContent.toLowerCase().includes(query)
            );
        });

        displayRows(1);
    }

    searchInput.addEventListener('input', filterRows);
    displayRows(1); // Initial display
});
</script>

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