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

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

$adminError = '';
$adminSuccess = '';

try {
    $adminCount = admin_count_users();
} catch (Throwable $e) {
    error_log('Admin bootstrap error: ' . $e->getMessage());
    $adminCount = 0;
    $adminError = 'Unable to load admin access right now. Please try again in a moment.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loginType = $_POST['login_type'] ?? '';

    if ($loginType === 'admin_setup' && $adminCount === 0) {
        $displayName = trim((string) ($_POST['display_name'] ?? ''));
        $email = strtolower(trim((string) ($_POST['email'] ?? '')));
        $password = (string) ($_POST['password'] ?? '');
        $passwordConfirm = (string) ($_POST['password_confirm'] ?? '');

        if ($displayName === '') {
            $adminError = 'Enter an admin name to finish setup.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $adminError = 'Enter a valid admin email address.';
        } elseif (strlen($password) < 10) {
            $adminError = 'Admin password must be at least 10 characters.';
        } elseif ($password !== $passwordConfirm) {
            $adminError = 'Admin passwords do not match.';
        } else {
            try {
                $newAdminId = admin_create_user($email, $password, $displayName);
                admin_login_user([
                    'id' => $newAdminId,
                    'email' => $email,
                    'display_name' => $displayName,
                ]);
                admin_set_flash('Admin access has been created successfully.');
                header('Location: admin.php');
                exit;
            } catch (PDOException $e) {
                error_log('Admin setup failed: ' . $e->getMessage());
                $adminError = 'Could not create the admin user. Please try a different email.';
            }
        }
    }

    if ($loginType === 'admin_login' && $adminCount > 0) {
        $email = strtolower(trim((string) ($_POST['email'] ?? '')));
        $password = (string) ($_POST['password'] ?? '');

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
            $adminError = 'Enter your admin email and password.';
        } else {
            try {
                $admin = admin_get_by_email($email);
                if ($admin && password_verify($password, $admin['password_hash'])) {
                    admin_login_user($admin);
                    header('Location: admin.php');
                    exit;
                }
                $adminError = 'Invalid admin email or password.';
            } catch (PDOException $e) {
                error_log('Admin login failed: ' . $e->getMessage());
                $adminError = 'Admin login is temporarily unavailable.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login | Webinar Platform</title>
    <meta name="description" content="Secure admin login for the webinar registration platform.">
    <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 {
            --primary-color: #2c4bd1;
            --primary-hover: #1029a0;
            --background-start: #071659;
            --background-end: #1029a0;
            --card-background: rgba(9, 24, 47, 0.8);
            --card-soft: rgba(221, 226, 253, 0.08);
            --text-color: #f3f9ff;
            --muted-text: #bbc8fb;
            --input-border: rgba(221, 226, 253, 0.18);
            --input-focus-border: #6ed4ff;
            --error-color: #ff99a9;
            --success-color: #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;
            --button-shadow: 0 18px 36px rgba(11, 32, 131, 0.34);
        }
        * { box-sizing: border-box; }
        body {
            font-family: var(--font-body);
            background:
                radial-gradient(circle at top left, rgba(221, 226, 253, 0.22), transparent 24%),
                radial-gradient(circle at bottom right, rgba(110, 212, 255, 0.12), transparent 28%),
                linear-gradient(135deg, var(--background-start) 0%, #1029a0 55%, var(--background-end) 100%);
            color: var(--text-color);
            margin: 0;
            min-height: 100vh;
            padding: 32px 20px;
        }
        .shell {
            width: 100%;
            max-width: 760px;
            margin: 0 auto;
        }
        .brand {
            text-align: center;
            margin-bottom: 2rem;
        }
        .brand-name {
            font-family: var(--font-display);
            font-size: 32px;
            font-weight: 700;
            letter-spacing: -0.04em;
            margin: 0 0 0.5rem;
        }
        .brand-copy {
            color: var(--muted-text);
            max-width: 700px;
            margin: 0 auto;
        }
        .grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 24px;
            align-items: start;
        }
        .card {
            background: var(--card-background);
            border-radius: 24px;
            padding: 28px;
            border: 1px solid var(--input-border);
            box-shadow: 0 24px 60px rgba(3, 11, 25, 0.35);
            backdrop-filter: blur(16px);
        }
        .eyebrow {
            display: inline-block;
            padding: 7px 12px;
            border-radius: 999px;
            background: rgba(110, 212, 255, 0.12);
            color: #d9f6ff;
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            margin-bottom: 0.9rem;
        }
        h1, h2 {
            font-family: var(--font-display);
            letter-spacing: -0.04em;
            margin-top: 0;
        }
        h1 { font-size: 40px; margin-bottom: 0.85rem; }
        h2 { font-size: 26px; margin-bottom: 0.6rem; }
        .subtitle, .helper, .notice {
            color: var(--muted-text);
            line-height: 1.6;
        }
        .notice {
            background: var(--card-soft);
            border: 1px solid rgba(221, 226, 253, 0.12);
            border-radius: 16px;
            padding: 14px 16px;
            margin-bottom: 1rem;
        }
        .status {
            padding: 12px 14px;
            border-radius: 14px;
            margin-bottom: 1rem;
            font-size: 0.95rem;
        }
        .status.error {
            background: rgba(255, 153, 169, 0.12);
            border: 1px solid rgba(255, 153, 169, 0.25);
            color: #ffd7de;
        }
        .status.success {
            background: rgba(24, 209, 179, 0.12);
            border: 1px solid rgba(24, 209, 179, 0.24);
            color: #d7fff6;
        }
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 14px;
        }
        .form-group {
            margin-bottom: 1rem;
        }
        .form-group.full {
            grid-column: 1 / -1;
        }
        label {
            display: block;
            margin-bottom: 0.45rem;
            font-weight: 600;
            font-size: 0.9rem;
        }
        input {
            width: 100%;
            padding: 13px 14px;
            border: 1px solid var(--input-border);
            border-radius: 12px;
            font-size: 16px;
            background: rgba(221, 226, 253, 0.08);
            color: var(--text-color);
        }
        input::placeholder { color: var(--muted-text); }
        input:focus {
            outline: none;
            border-color: var(--input-focus-border);
            box-shadow: 0 0 0 3px rgba(110, 212, 255, 0.14);
            background: rgba(221, 226, 253, 0.12);
        }
        .btn {
            width: 100%;
            border: 1px solid rgba(221, 226, 253, 0.16);
            border-radius: 14px;
            padding: 14px 18px;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
            color: #fff;
            font-family: var(--font-display);
            font-weight: 700;
            font-size: 1rem;
            cursor: pointer;
            box-shadow: var(--button-shadow);
        }
        .btn:hover { transform: translateY(-1px); }
        .actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 1rem;
        }
        .text-link {
            color: #d7ecff;
            text-decoration: none;
            font-weight: 600;
        }
        .text-link:hover { text-decoration: underline; }
        ul.feature-list {
            margin: 1rem 0 0;
            padding-left: 1.2rem;
            color: var(--muted-text);
        }
        ul.feature-list li { margin-bottom: 0.55rem; }
        @media (max-width: 900px) {
            .grid { grid-template-columns: 1fr; }
        }
        @media (max-width: 640px) {
            h1 { font-size: 32px; }
            .card { padding: 22px; }
            .form-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <main class="shell">
        <header class="brand">
            <div class="eyebrow">Admin access</div>
            <h1 class="brand-name">Secure admin login for your webinar workspace</h1>
            <p class="brand-copy">Use the admin area to manage registrations, edit attendee data, export CSV, and track daily signup trends.</p>
        </header>

        <section class="grid" aria-label="Login options">
            <article class="card">
                <div class="eyebrow">Admin</div>
                <h2><?php echo $adminCount === 0 ? 'Create the first admin account' : 'Admin login'; ?></h2>
                <p class="subtitle">
                    <?php echo $adminCount === 0
                        ? 'The previous hardcoded admin password has been removed. Create a real admin account to unlock the dashboard.'
                        : 'Sign in with your saved admin credentials to access registrations and analytics.'; ?>
                </p>

                <?php if ($adminError !== ''): ?>
                    <div class="status error"><?php echo htmlspecialchars($adminError); ?></div>
                <?php endif; ?>
                <?php if ($adminSuccess !== ''): ?>
                    <div class="status success"><?php echo htmlspecialchars($adminSuccess); ?></div>
                <?php endif; ?>

                <?php if ($adminCount === 0): ?>
                    <div class="notice">First-run setup is only shown until one admin account exists. After that, access is password-hashed and database-backed.</div>
                    <form method="POST" action="login.php" novalidate>
                        <input type="hidden" name="login_type" value="admin_setup">
                        <div class="form-grid">
                            <div class="form-group full">
                                <label for="display_name">Admin name</label>
                                <input type="text" id="display_name" name="display_name" placeholder="Jane Admin" required>
                            </div>
                            <div class="form-group full">
                                <label for="admin_email">Admin email</label>
                                <input type="email" id="admin_email" name="email" placeholder="admin@yourdomain.com" required>
                            </div>
                            <div class="form-group">
                                <label for="admin_password">Password</label>
                                <input type="password" id="admin_password" name="password" minlength="10" placeholder="At least 10 characters" required>
                            </div>
                            <div class="form-group">
                                <label for="admin_password_confirm">Confirm password</label>
                                <input type="password" id="admin_password_confirm" name="password_confirm" minlength="10" placeholder="Repeat password" required>
                            </div>
                        </div>
                        <button type="submit" class="btn">Create admin account</button>
                    </form>
                <?php else: ?>
                    <form method="POST" action="login.php" novalidate>
                        <input type="hidden" name="login_type" value="admin_login">
                        <div class="form-group">
                            <label for="admin_login_email">Admin email</label>
                            <input type="email" id="admin_login_email" name="email" placeholder="admin@yourdomain.com" required>
                        </div>
                        <div class="form-group">
                            <label for="admin_login_password">Password</label>
                            <input type="password" id="admin_login_password" name="password" placeholder="Your admin password" required>
                        </div>
                        <button type="submit" class="btn">Open admin dashboard</button>
                    </form>
                <?php endif; ?>

                <ul class="feature-list">
                    <li>See all webinar registrations in one place.</li>
                    <li>Edit attendee details and archive old records safely.</li>
                    <li>Export filtered data to CSV and watch the daily chart update automatically.</li>
                </ul>
            </article>

        </section>
    </main>
</body>
</html>
