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

if (isset($_GET['logout']) && $_GET['logout'] === '1') {
    unset($_SESSION['user_id']);
    session_regenerate_id(true);
    header('Location: login.php');
    exit;
}

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

function format_dashboard_datetime(?string $scheduledAt, ?string $timezone): string {
    if (!$scheduledAt) {
        return 'Schedule to be announced';
    }

    try {
        $date = new DateTime($scheduledAt, new DateTimeZone('UTC'));
        if (!empty($timezone) && in_array($timezone, timezone_identifiers_list(), true)) {
            $date->setTimezone(new DateTimeZone($timezone));
            return $date->format('l, F j, Y \a\t g:i A T');
        }

        return $date->format('l, F j, Y \a\t g:i A T');
    } catch (Throwable $e) {
        return $scheduledAt;
    }
}

$attendee = null;
$webinar = null;
$error = '';
$user_id = (int) $_SESSION['user_id'];

try {
    $stmt = db()->prepare('SELECT * FROM attendees WHERE id = ? AND deleted_at IS NULL');
    $stmt->execute([$user_id]);
    $attendee = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($attendee) {
        $stmt = db()->prepare('SELECT * FROM webinars WHERE id = ?');
        $stmt->execute([(int) $attendee['webinar_id']]);
        $webinar = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        $error = 'Could not find your active registration details.';
    }
} catch (PDOException $e) {
    error_log('Dashboard load failed: ' . $e->getMessage());
    $error = 'Dashboard is temporarily unavailable. Please try again later.';
}

$participantName = trim((string) (($attendee['first_name'] ?? '') . ' ' . ($attendee['last_name'] ?? '')));
$participantName = $participantName !== '' ? $participantName : ((string) ($attendee['email'] ?? 'Guest'));
$joinLink = $attendee ? 'join.php?id=' . rawurlencode(base64_encode((string) $attendee['id'])) : 'login.php';
$webinarDate = $webinar ? format_dashboard_datetime($webinar['scheduled_at'] ?? null, $attendee['timezone'] ?? null) : 'Schedule to be announced';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Webinar Dashboard | AppWizzy</title>
    <meta name="description" content="Access your webinar registration details and join link for the AppWizzy event.">
    <meta name="robots" content="noindex, nofollow">
    <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">
    <style>
        :root {
            --bg-start: #071659;
            --bg-end: #1029a0;
            --surface: rgba(9, 24, 47, 0.82);
            --surface-soft: rgba(221, 226, 253, 0.08);
            --line: rgba(221, 226, 253, 0.16);
            --text-main: #f3f9ff;
            --text-soft: #dde2fd;
            --text-muted: #bbc8fb;
            --accent: #6ed4ff;
            --accent-strong: #2c4bd1;
            --success: #18d1b3;
            --danger: #ff99a9;
            --shadow: 0 30px 80px rgba(2, 10, 24, 0.48);
            --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;
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            min-height: 100vh;
            font-family: var(--font-body);
            color: var(--text-main);
            background:
                radial-gradient(circle at top left, rgba(110, 212, 255, 0.18), transparent 28%),
                radial-gradient(circle at bottom right, rgba(44, 75, 209, 0.20), transparent 32%),
                linear-gradient(145deg, var(--bg-start) 0%, var(--bg-end) 100%);
        }
        .page {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 32px 20px;
        }
        .card {
            width: 100%;
            max-width: 960px;
            background: var(--surface);
            border: 1px solid var(--line);
            border-radius: 28px;
            box-shadow: var(--shadow);
            backdrop-filter: blur(18px);
            overflow: hidden;
        }
        .shell {
            display: grid;
            grid-template-columns: 1.15fr 0.85fr;
        }
        .main, .aside { padding: 40px; }
        .aside {
            background: linear-gradient(180deg, rgba(11, 32, 131, 0.62), rgba(16, 41, 160, 0.82));
            border-left: 1px solid var(--line);
        }
        .eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(110, 212, 255, 0.12);
            color: var(--accent);
            font-size: 0.88rem;
            font-weight: 700;
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }
        h1, h2 { font-family: var(--font-display); margin: 0 0 14px; }
        h1 { font-size: clamp(2.1rem, 4vw, 3.2rem); line-height: 1.02; }
        h2 { font-size: 1.2rem; }
        p { color: var(--text-soft); line-height: 1.65; }
        .lead { font-size: 1.05rem; max-width: 44ch; }
        .notice {
            margin-top: 20px;
            padding: 16px 18px;
            border-radius: 18px;
            border: 1px solid rgba(255, 153, 169, 0.2);
            background: rgba(255, 153, 169, 0.12);
            color: #fff;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
            margin-top: 28px;
        }
        .stat {
            padding: 18px;
            border-radius: 20px;
            background: var(--surface-soft);
            border: 1px solid rgba(221, 226, 253, 0.12);
        }
        .stat-label {
            color: var(--text-muted);
            font-size: 0.82rem;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            margin-bottom: 8px;
        }
        .stat-value {
            font-size: 1.05rem;
            font-weight: 700;
            color: var(--text-main);
        }
        .actions {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 28px;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 14px 20px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            transition: transform 0.18s ease, box-shadow 0.18s ease, background 0.18s ease;
        }
        .btn:hover { transform: translateY(-1px); }
        .btn-primary {
            background: linear-gradient(135deg, #6ed4ff 0%, #2c4bd1 100%);
            color: #071659;
            box-shadow: 0 18px 36px rgba(44, 75, 209, 0.28);
        }
        .btn-secondary {
            background: rgba(221, 226, 253, 0.10);
            border: 1px solid rgba(221, 226, 253, 0.18);
            color: var(--text-main);
        }
        .aside-card {
            padding: 20px;
            border-radius: 20px;
            background: rgba(221, 226, 253, 0.08);
            border: 1px solid rgba(221, 226, 253, 0.12);
            margin-bottom: 16px;
        }
        .aside-card strong {
            display: block;
            margin-bottom: 8px;
            font-size: 1rem;
        }
        .aside small {
            color: var(--text-muted);
        }
        .footer-link {
            margin-top: 18px;
            display: inline-block;
            color: var(--text-soft);
            text-decoration: none;
        }
        @media (max-width: 860px) {
            .shell { grid-template-columns: 1fr; }
            .aside { border-left: 0; border-top: 1px solid var(--line); }
            .main, .aside { padding: 28px; }
            .stats { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <main class="page">
        <section class="card">
            <div class="shell">
                <div class="main">
                    <span class="eyebrow">Registered attendee</span>
                    <h1>Your webinar dashboard</h1>
                    <?php if ($error !== ''): ?>
                        <div class="notice"><?php echo htmlspecialchars($error); ?></div>
                    <?php elseif ($attendee && $webinar): ?>
                        <p class="lead">Hi <strong><?php echo htmlspecialchars($participantName); ?></strong> — your seat is confirmed. Use the join button below when it is time to enter the webinar room.</p>

                        <div class="stats" aria-label="Registration details">
                            <div class="stat">
                                <div class="stat-label">Webinar</div>
                                <div class="stat-value"><?php echo htmlspecialchars((string) ($webinar['title'] ?? 'Upcoming webinar')); ?></div>
                            </div>
                            <div class="stat">
                                <div class="stat-label">Scheduled time</div>
                                <div class="stat-value"><?php echo htmlspecialchars($webinarDate); ?></div>
                            </div>
                            <div class="stat">
                                <div class="stat-label">Email</div>
                                <div class="stat-value"><?php echo htmlspecialchars((string) ($attendee['email'] ?? '—')); ?></div>
                            </div>
                            <div class="stat">
                                <div class="stat-label">Timezone</div>
                                <div class="stat-value"><?php echo htmlspecialchars((string) (($attendee['timezone'] ?? '') !== '' ? $attendee['timezone'] : 'UTC')); ?></div>
                            </div>
                        </div>

                        <div class="actions">
                            <a href="<?php echo htmlspecialchars($joinLink); ?>" class="btn btn-primary">Join webinar</a>
                            <a href="index.php" class="btn btn-secondary">Back to site</a>
                            <a href="dashboard.php?logout=1" class="btn btn-secondary">Log out</a>
                        </div>
                    <?php else: ?>
                        <div class="notice">Could not find your registration details.</div>
                    <?php endif; ?>
                </div>
                <aside class="aside">
                    <h2>What to expect</h2>
                    <div class="aside-card">
                        <strong>Live product session</strong>
                        <small>See how AppWizzy goes from idea to a working app with a real database and a real deployment flow.</small>
                    </div>
                    <div class="aside-card">
                        <strong>Practical takeaways</strong>
                        <small>Architecture, ownership, scaling, and why generated apps should stay editable.</small>
                    </div>
                    <div class="aside-card">
                        <strong>Need help?</strong>
                        <small>If your details look wrong, return to the main page and submit the form again, or contact the organizer.</small>
                    </div>
                    <a class="footer-link" href="login.php">← Back to login</a>
                </aside>
            </div>
        </section>
    </main>
</body>
</html>
