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

function resolve_attendee_id(): ?int {
    if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])) {
        return (int) $_SESSION['user_id'];
    }

    $raw = isset($_GET['id']) ? trim((string) $_GET['id']) : '';
    if ($raw === '') {
        return null;
    }

    if (ctype_digit($raw)) {
        return (int) $raw;
    }

    $decoded = base64_decode(strtr($raw, ' ', '+'), true);
    if ($decoded !== false && ctype_digit($decoded)) {
        return (int) $decoded;
    }

    return null;
}

function format_join_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');
    } catch (Throwable $e) {
        return $scheduledAt;
    }
}

$attendeeId = resolve_attendee_id();
if ($attendeeId === null) {
    http_response_code(400);
    echo 'Invalid webinar access link.';
    exit;
}

$attendee = null;
$webinar = null;

try {
    $stmt = db()->prepare('SELECT * FROM attendees WHERE id = ? AND deleted_at IS NULL');
    $stmt->execute([$attendeeId]);
    $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);
    }
} catch (PDOException $e) {
    error_log('Join page lookup failed: ' . $e->getMessage());
}

if (!$attendee || !$webinar) {
    http_response_code(404);
    echo 'Registration not found.';
    exit;
}

$participantName = trim((string) (($attendee['first_name'] ?? '') . ' ' . ($attendee['last_name'] ?? '')));
$participantName = $participantName !== '' ? $participantName : ((string) ($attendee['email'] ?? 'Guest'));
$scheduledLabel = format_join_datetime($webinar['scheduled_at'] ?? null, $attendee['timezone'] ?? null);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Join Webinar | AppWizzy</title>
    <meta name="description" content="Join the AppWizzy webinar room and review your registration details.">
    <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.84);
            --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;
            --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;
            display: grid;
            place-items: center;
            padding: 24px;
            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%);
        }
        .card {
            width: 100%;
            max-width: 840px;
            padding: 36px;
            background: var(--surface);
            border: 1px solid var(--line);
            border-radius: 28px;
            box-shadow: 0 30px 80px rgba(2, 10, 24, 0.48);
            backdrop-filter: blur(18px);
        }
        .badge {
            display: inline-flex;
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(24, 209, 179, 0.14);
            color: var(--success);
            font-size: 0.88rem;
            font-weight: 700;
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }
        h1 {
            font-family: var(--font-display);
            font-size: clamp(2.1rem, 4vw, 3rem);
            margin: 16px 0 14px;
            line-height: 1.02;
        }
        p { color: var(--text-soft); line-height: 1.65; }
        .grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
            margin: 28px 0;
        }
        .item {
            padding: 18px;
            border-radius: 20px;
            background: var(--surface-soft);
            border: 1px solid rgba(221, 226, 253, 0.12);
        }
        .item-label {
            color: var(--text-muted);
            font-size: 0.82rem;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            margin-bottom: 8px;
        }
        .item-value {
            font-weight: 700;
            font-size: 1.02rem;
        }
        .actions {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 24px;
        }
        .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;
        }
        .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);
        }
        @media (max-width: 720px) {
            .card { padding: 28px; }
            .grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <main class="card">
        <span class="badge">Access confirmed</span>
        <h1>Welcome, <?php echo htmlspecialchars($participantName); ?>!</h1>
        <p>Your registration is active. When the live room is available, this page is where you can connect attendees to the webinar experience.</p>

        <section class="grid" aria-label="Registration summary">
            <div class="item">
                <div class="item-label">Webinar</div>
                <div class="item-value"><?php echo htmlspecialchars((string) ($webinar['title'] ?? 'Upcoming webinar')); ?></div>
            </div>
            <div class="item">
                <div class="item-label">Scheduled time</div>
                <div class="item-value"><?php echo htmlspecialchars($scheduledLabel); ?></div>
            </div>
            <div class="item">
                <div class="item-label">Registered email</div>
                <div class="item-value"><?php echo htmlspecialchars((string) ($attendee['email'] ?? '—')); ?></div>
            </div>
            <div class="item">
                <div class="item-label">Timezone</div>
                <div class="item-value"><?php echo htmlspecialchars((string) (($attendee['timezone'] ?? '') !== '' ? $attendee['timezone'] : 'UTC')); ?></div>
            </div>
        </section>

        <div class="actions">
            <a href="dashboard.php" class="btn btn-primary">Back to dashboard</a>
            <a href="index.php" class="btn btn-secondary">Open main site</a>
        </div>
    </main>
</body>
</html>
