<?php
session_start();
require_once 'db/config.php';
require_once 'includes/admin_auth.php';

admin_require_login();

function format_admin_datetime(?string $value): string {
    if (!$value) {
        return '—';
    }

    try {
        return (new DateTime($value))->format('M j, Y • g:i A');
    } catch (Exception $e) {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}

function bind_named_values(PDOStatement $stmt, array $params): void {
    foreach ($params as $name => $value) {
        $stmt->bindValue($name, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
}

$message = admin_get_flash();

$pdo = db();
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$selected_webinar_id = isset($_GET['webinar_id']) && is_numeric($_GET['webinar_id']) ? max(0, (int) $_GET['webinar_id']) : 0;

$webinars = $pdo->query('SELECT id, title, scheduled_at FROM webinars ORDER BY scheduled_at DESC, id DESC')->fetchAll(PDO::FETCH_ASSOC);

$where_parts = ['a.deleted_at IS NULL'];
$params = [];
if ($selected_webinar_id > 0) {
    $where_parts[] = 'a.webinar_id = :webinar_id';
    $params[':webinar_id'] = $selected_webinar_id;
}
$where_sql = 'WHERE ' . implode(' AND ', $where_parts);

$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM attendees a {$where_sql}");
bind_named_values($count_stmt, $params);
$count_stmt->execute();
$total_records = (int) $count_stmt->fetchColumn();

$total_pages = max(1, (int) ceil($total_records / $records_per_page));
if ($page > $total_pages) {
    $page = $total_pages;
}
$offset = ($page - 1) * $records_per_page;

$today_stmt = $pdo->prepare("SELECT COUNT(*) FROM attendees a {$where_sql} AND DATE(a.created_at) = CURDATE()");
bind_named_values($today_stmt, $params);
$today_stmt->execute();
$today_count = (int) $today_stmt->fetchColumn();

$last7_stmt = $pdo->prepare("SELECT COUNT(*) FROM attendees a {$where_sql} AND a.created_at >= (NOW() - INTERVAL 7 DAY)");
bind_named_values($last7_stmt, $params);
$last7_stmt->execute();
$last_7_days_count = (int) $last7_stmt->fetchColumn();

$latest_stmt = $pdo->prepare("SELECT MAX(a.created_at) FROM attendees a {$where_sql}");
bind_named_values($latest_stmt, $params);
$latest_stmt->execute();
$latest_registration_at = $latest_stmt->fetchColumn();

$company_stmt = $pdo->prepare("SELECT COUNT(DISTINCT NULLIF(TRIM(a.company), '')) FROM attendees a {$where_sql}");
bind_named_values($company_stmt, $params);
$company_stmt->execute();
$unique_companies = (int) $company_stmt->fetchColumn();

$attendees_sql = "SELECT
        a.id,
        a.webinar_id,
        a.first_name,
        a.last_name,
        a.email,
        a.company,
        a.how_did_you_hear,
        a.timezone,
        a.consented,
        a.created_at,
        w.title AS webinar_title,
        w.scheduled_at AS webinar_scheduled_at
    FROM attendees a
    LEFT JOIN webinars w ON w.id = a.webinar_id
    {$where_sql}
    ORDER BY a.created_at DESC, a.id DESC
    LIMIT :limit OFFSET :offset";
$attendees_stmt = $pdo->prepare($attendees_sql);
bind_named_values($attendees_stmt, $params);
$attendees_stmt->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
$attendees_stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$attendees_stmt->execute();
$attendees = $attendees_stmt->fetchAll(PDO::FETCH_ASSOC);

$chart_stmt = $pdo->prepare("SELECT DATE(a.created_at) AS registration_day, COUNT(*) AS user_count
    FROM attendees a
    {$where_sql}
    GROUP BY DATE(a.created_at)
    ORDER BY DATE(a.created_at)");
bind_named_values($chart_stmt, $params);
$chart_stmt->execute();
$chart_data = $chart_stmt->fetchAll(PDO::FETCH_ASSOC);

$selected_webinar = null;
foreach ($webinars as $webinar) {
    if ((int) $webinar['id'] === $selected_webinar_id) {
        $selected_webinar = $webinar;
        break;
    }
}

$chart_labels = json_encode(array_column($chart_data, 'registration_day'));
$chart_values = json_encode(array_column($chart_data, 'user_count'));
$export_link = 'export_csv.php' . ($selected_webinar_id > 0 ? '?webinar_id=' . urlencode((string) $selected_webinar_id) : '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | Webinar Registrations</title>
    <meta name="description" content="Admin dashboard for webinar registrations, attendee management, CSV exports, and daily registration charts.">
    <meta name="robots" content="noindex, nofollow">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Space+Grotesk:wght@500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --bg-start: #0b2083;
            --bg-end: #1029a0;
            --surface: rgba(11, 32, 131, 0.40);
            --surface-soft: rgba(16, 41, 160, 0.32);
            --line: rgba(221, 226, 253, 0.18);
            --text-main: #f3f9ff;
            --text-soft: #dde2fd;
            --text-muted: #97acd0;
            --accent: #2c4bd1;
            --accent-strong: #1029a0;
            --success: #18d1b3;
            --danger: #ff6b81;
            --font-body: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            --font-display: "Space Grotesk", "Inter", system-ui, sans-serif;
            --button-shadow: 0 16px 30px rgba(11, 32, 131, 0.26);
        }
        body {
            font-family: var(--font-body);
            min-height: 100vh;
            margin: 0;
            background:
                radial-gradient(circle at top left, rgba(221, 226, 253, 0.22), transparent 28%),
                linear-gradient(135deg, var(--bg-start) 0%, #1029a0 55%, var(--bg-end) 100%);
            color: var(--text-main);
        }
        .admin-shell {
            max-width: 1380px;
            padding-top: 40px;
            padding-bottom: 40px;
        }
        h1, h2, h3, .h5, .btn, .page-link, th, label {
            font-family: var(--font-display);
        }
        h1 {
            font-size: 2.2rem;
            font-weight: 700;
            letter-spacing: -0.04em;
            margin-bottom: 0.35rem;
        }
        .lead-copy,
        .text-muted {
            color: var(--text-muted) !important;
        }
        .panel-card,
        .table-shell,
        .summary-card,
        .toolbar-card {
            background: var(--surface);
            border: 1px solid var(--line);
            border-radius: 22px;
            box-shadow: 0 25px 60px rgba(3, 11, 25, 0.38);
            backdrop-filter: blur(16px);
        }
        .panel-card,
        .summary-card,
        .toolbar-card {
            padding: 1.5rem;
        }
        .table-shell {
            margin-top: 1rem;
            padding: 0.35rem;
            overflow: hidden;
        }
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
            margin-top: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .summary-label {
            color: var(--text-soft);
            font-size: 0.9rem;
            margin-bottom: 0.45rem;
        }
        .summary-value {
            font-size: 2rem;
            font-weight: 800;
            line-height: 1;
        }
        .summary-meta {
            margin-top: 0.6rem;
            color: var(--text-muted);
            font-size: 0.9rem;
        }
        .toolbar-card {
            display: flex;
            align-items: end;
            justify-content: space-between;
            gap: 1rem;
            flex-wrap: wrap;
            margin-top: 1rem;
        }
        .filter-form {
            display: flex;
            align-items: end;
            gap: 0.75rem;
            flex-wrap: wrap;
        }
        .form-select,
        .form-control {
            min-width: 260px;
            background: rgba(221, 226, 253, 0.08);
            border-color: rgba(221, 226, 253, 0.18);
            color: var(--text-main);
        }
        .form-select:focus,
        .form-control:focus {
            background: rgba(221, 226, 253, 0.10);
            color: var(--text-main);
            border-color: rgba(44, 75, 209, 0.65);
            box-shadow: 0 0 0 0.2rem rgba(187, 200, 251, 0.18);
        }
        .table {
            --bs-table-bg: transparent;
            --bs-table-color: var(--text-main);
            --bs-table-striped-bg: rgba(255, 255, 255, 0.03);
            --bs-table-striped-color: var(--text-main);
            --bs-table-border-color: rgba(221, 226, 253, 0.12);
            margin-bottom: 0;
        }
        th {
            color: var(--text-soft);
            font-size: 0.85rem;
            letter-spacing: 0.04em;
            text-transform: uppercase;
            white-space: nowrap;
        }
        td {
            vertical-align: middle;
        }
        .tag {
            display: inline-flex;
            align-items: center;
            padding: 0.32rem 0.7rem;
            border-radius: 999px;
            background: rgba(34, 199, 255, 0.14);
            color: var(--text-main);
            font-size: 0.84rem;
            border: 1px solid rgba(34, 199, 255, 0.18);
        }
        .attendee-name {
            font-weight: 700;
        }
        .attendee-meta,
        .webinar-meta {
            display: block;
            margin-top: 0.25rem;
            color: var(--text-muted);
            font-size: 0.86rem;
        }
        .btn {
            border-radius: 14px;
            font-weight: 700;
            letter-spacing: 0.02em;
        }
        .btn-primary {
            background: linear-gradient(135deg, var(--accent) 0%, var(--accent-strong) 100%);
            border: 1px solid rgba(221, 226, 253, 0.14);
            box-shadow: var(--button-shadow);
        }
        .btn-success {
            background: linear-gradient(135deg, #18d1b3 0%, #0b8f7a 100%);
            border-color: transparent;
            box-shadow: 0 16px 30px rgba(24, 209, 179, 0.18);
        }
        .btn-outline-light {
            border-color: rgba(221, 226, 253, 0.28);
        }
        .pagination .page-link {
            color: var(--text-main);
            background: rgba(221, 226, 253, 0.05);
            border-color: rgba(221, 226, 253, 0.14);
        }
        .pagination .page-item.active .page-link {
            background: var(--accent);
            border-color: transparent;
        }
        .alert {
            border-radius: 16px;
            margin-top: 1.2rem;
        }
        code {
            color: var(--accent-soft, #bbc8fb);
        }
        @media (max-width: 991px) {
            .admin-shell {
                padding-top: 24px;
            }
            .summary-value {
                font-size: 1.7rem;
            }
            .form-select,
            .form-control {
                min-width: 210px;
            }
        }
    </style>
</head>
<body>
    <main class="container admin-shell">
        <header>
            <h1>Webinar registrations dashboard</h1>
            <p class="lead-copy mb-0">Welcome, <?php echo htmlspecialchars(admin_current_name()); ?>. Review attendee data, edit registrations, export CSV, and monitor daily signup volume.</p>
        </header>

        <?php if ($message): ?>
            <div class="alert alert-info"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>

        <section class="toolbar-card" aria-label="Dashboard filters and actions">
            <form class="filter-form" method="GET" action="admin.php">
                <div>
                    <label for="webinar_id" class="form-label mb-2">Webinar filter</label>
                    <select class="form-select" id="webinar_id" name="webinar_id">
                        <option value="0">All webinars</option>
                        <?php foreach ($webinars as $webinar): ?>
                            <option value="<?php echo (int) $webinar['id']; ?>" <?php echo (int) $webinar['id'] === $selected_webinar_id ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($webinar['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="d-flex gap-2 flex-wrap">
                    <button type="submit" class="btn btn-primary">Apply filter</button>
                    <a href="admin.php" class="btn btn-outline-light">Reset</a>
                </div>
            </form>
            <div class="d-flex gap-2 flex-wrap">
                <a href="<?php echo htmlspecialchars($export_link); ?>" class="btn btn-success">Download CSV</a>
                <a href="index.php" class="btn btn-outline-light">View site</a>
                <a href="login.php?logout=1" class="btn btn-outline-light">Log out</a>
            </div>
        </section>

        <section class="summary-grid" aria-label="Registration summary">
            <article class="summary-card">
                <div class="summary-label">Total registrations</div>
                <div class="summary-value"><?php echo number_format($total_records); ?></div>
                <div class="summary-meta">Active attendees<?php echo $selected_webinar ? ' for the selected webinar' : ' across all webinars'; ?>.</div>
            </article>
            <article class="summary-card">
                <div class="summary-label">Registered today</div>
                <div class="summary-value"><?php echo number_format($today_count); ?></div>
                <div class="summary-meta">New signups recorded on <?php echo (new DateTime())->format('M j, Y'); ?>.</div>
            </article>
            <article class="summary-card">
                <div class="summary-label">Last 7 days</div>
                <div class="summary-value"><?php echo number_format($last_7_days_count); ?></div>
                <div class="summary-meta">Rolling weekly registrations based on <code>created_at</code>.</div>
            </article>
            <article class="summary-card">
                <div class="summary-label">Companies represented</div>
                <div class="summary-value"><?php echo number_format($unique_companies); ?></div>
                <div class="summary-meta">Unique non-empty company names among active attendees.</div>
            </article>
            <article class="summary-card">
                <div class="summary-label">Latest registration</div>
                <div class="summary-value" style="font-size: 1.15rem; line-height: 1.35;"><?php echo htmlspecialchars(format_admin_datetime($latest_registration_at)); ?></div>
                <div class="summary-meta">Most recent active attendee creation timestamp.</div>
            </article>
        </section>

        <section class="panel-card" aria-labelledby="daily-registrations-title">
            <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                <div>
                    <h2 id="daily-registrations-title" class="h5 mb-1">Daily registrations</h2>
                    <p class="text-muted mb-0">Chart based on attendee <code>created_at</code>, grouped by registration day<?php echo $selected_webinar ? ' for the selected webinar' : ''; ?>.</p>
                </div>
                <button id="downloadChartBtn" class="btn btn-sm btn-primary" type="button">Save as Image</button>
            </div>
            <div style="max-width: 840px; margin: auto;">
                <canvas id="registrationsChart"></canvas>
            </div>
        </section>

        <section class="toolbar-card" aria-labelledby="registered-attendees-title">
            <div>
                <h2 id="registered-attendees-title" class="h5 mb-1">Registered attendees</h2>
                <p class="text-muted mb-0">
                    <?php if ($selected_webinar): ?>
                        Showing active records for <strong><?php echo htmlspecialchars($selected_webinar['title']); ?></strong>.
                    <?php else: ?>
                        Showing active records for all webinars, newest registrations first.
                    <?php endif; ?>
                </p>
            </div>
        </section>

        <div class="table-responsive table-shell">
            <table class="table table-striped align-middle">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Attendee</th>
                        <th>Email</th>
                        <th>Company</th>
                        <th>Source</th>
                        <th>Timezone</th>
                        <th>Webinar</th>
                        <th>Registered at</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($attendees)): ?>
                        <tr>
                            <td colspan="9" class="text-center py-4">No attendees found for this filter yet.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($attendees as $attendee): ?>
                            <tr>
                                <td><?php echo (int) $attendee['id']; ?></td>
                                <td>
                                    <span class="attendee-name"><?php echo htmlspecialchars(trim(($attendee['first_name'] ?? '') . ' ' . ($attendee['last_name'] ?? '')) ?: '—'); ?></span>
                                    <span class="attendee-meta">Consent: <?php echo !empty($attendee['consented']) ? 'Yes' : 'No'; ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($attendee['email'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars(($attendee['company'] ?? '') !== '' ? $attendee['company'] : '—'); ?></td>
                                <td><span class="tag"><?php echo htmlspecialchars(($attendee['how_did_you_hear'] ?? '') !== '' ? $attendee['how_did_you_hear'] : '—'); ?></span></td>
                                <td><?php echo htmlspecialchars(($attendee['timezone'] ?? '') !== '' ? $attendee['timezone'] : '—'); ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars(($attendee['webinar_title'] ?? '') !== '' ? $attendee['webinar_title'] : '—'); ?></strong>
                                    <span class="webinar-meta"><?php echo htmlspecialchars(format_admin_datetime($attendee['webinar_scheduled_at'] ?? null)); ?></span>
                                </td>
                                <td><?php echo htmlspecialchars(format_admin_datetime($attendee['created_at'] ?? null)); ?></td>
                                <td>
                                    <div class="d-flex gap-2 flex-wrap">
                                        <a href="edit_attendee.php?id=<?php echo (int) $attendee['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                        <form action="delete_attendee.php" method="POST" class="m-0" onsubmit="return confirm('Soft-delete attendee #<?php echo (int) $attendee['id']; ?>?');">
                                            <input type="hidden" name="id" value="<?php echo (int) $attendee['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-light">Archive</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($total_pages > 1): ?>
            <nav class="mt-4" aria-label="Attendee pagination">
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="admin.php?page=<?php echo $i; ?><?php echo $selected_webinar_id > 0 ? '&amp;webinar_id=' . urlencode((string) $selected_webinar_id) : ''; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </main>

    <script>
        const chartLabels = <?php echo $chart_labels ?: '[]'; ?>;
        const chartValues = <?php echo $chart_values ?: '[]'; ?>;
        const chartCtx = document.getElementById('registrationsChart');

        const registrationsChart = new Chart(chartCtx, {
            type: 'line',
            data: {
                labels: chartLabels,
                datasets: [{
                    label: 'Registrations per day',
                    data: chartValues,
                    fill: true,
                    tension: 0.35,
                    borderWidth: 3,
                    borderColor: '#22c7ff',
                    backgroundColor: 'rgba(34, 199, 255, 0.15)',
                    pointBackgroundColor: '#f3f9ff',
                    pointBorderColor: '#22c7ff',
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        labels: {
                            color: '#dde2fd'
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: { color: '#dde2fd' },
                        grid: { color: 'rgba(221, 226, 253, 0.08)' }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: '#dde2fd',
                            precision: 0
                        },
                        grid: { color: 'rgba(221, 226, 253, 0.08)' }
                    }
                }
            }
        });

        document.getElementById('downloadChartBtn').addEventListener('click', function () {
            const link = document.createElement('a');
            link.href = registrationsChart.toBase64Image('image/png', 1);
            link.download = 'registrations-per-day.png';
            link.click();
        });
    </script>
</body>
</html>
