<?php
define('SECURE_ACCESS', true);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// If already logged in, redirect away
redirectIfLoggedIn();

$token = isset($_GET['token']) ? trim($_GET['token']) : '';
$error = '';
$invitation = null;
$isValid = false;

if ($pdo === null) {
    die("Database connection is not initialized.");
}

// 1. Verify invitation token
if (!empty($token)) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM speaker_invitations WHERE token = ? AND status = 'pending'");
        $stmt->execute([$token]);
        $invitation = $stmt->fetch();
        
        if ($invitation) {
            $isValid = true;
        } else {
            $error = "This invitation token is invalid or has already been used.";
        }
    } catch (PDOException $e) {
        $error = "Database error verifying token: " . $e->getMessage();
    }
} else {
    $error = "An invitation token is required to access speaker onboarding.";
}

// 2. Handle Onboarding Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isValid) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $full_name = trim($_POST['full_name'] ?? '');
    $expertise = trim($_POST['expertise'] ?? '');
    $organization = trim($_POST['organization'] ?? '');
    $bio = trim($_POST['bio'] ?? '');
    $email = $invitation['email']; // Always pull from secure invitation record

    if (empty($username) || empty($password) || empty($full_name) || empty($expertise)) {
        $error = "Please fill in all required fields marked with *.";
    } else {
        try {
            // Check if username already exists
            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
            $check->execute([$username, $email]);
            
            if ($check->fetchColumn() > 0) {
                $error = "Username or Email already exists. Please choose a different username.";
            } else {
                // Begin Transaction to write User, Profile, and Accept Token
                $pdo->beginTransaction();

                $hashedPass = password_hash($password, PASSWORD_DEFAULT);
                
                // A. Insert User Account
                $ins_user = $pdo->prepare("
                    INSERT INTO users (username, email, password, role, status) 
                    VALUES (?, ?, ?, 'speaker', 'active')
                ");
                $ins_user->execute([$username, $email, $hashedPass]);
                $new_user_id = $pdo->lastInsertId();
                require_once __DIR__ . '/../includes/bonus_helper.php';
                awardSignupAndReferralBonuses($new_user_id);

                // B. Insert Speaker Profile
                $ins_profile = $pdo->prepare("
                    INSERT INTO speaker_profiles (user_id, full_name, bio, expertise, organization) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $ins_profile->execute([$new_user_id, $full_name, $bio, $expertise, $organization]);

                // C. Update Invitation Status
                $upd_invite = $pdo->prepare("UPDATE speaker_invitations SET status = 'accepted' WHERE id = ?");
                $upd_invite->execute([$invitation['id']]);

                $pdo->commit();

                // D. Auto Log In User
                $_SESSION['user_id'] = $new_user_id;
                $_SESSION['username'] = $username;
                $_SESSION['email'] = $email;
                $_SESSION['role'] = 'speaker';
                $_SESSION['status'] = 'active';
                $_SESSION['flash_success'] = "Onboarding complete! Welcome to EventPortal, Dr./Mr./Ms. $full_name!";
                
                header("Location: dashboard");
                exit();
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = "Transaction failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RENENET EDUCARE</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        html {
            font-size: 16px;
        }
        @media (max-width: 576px) {
            html { font-size: 14px; }
        }
        body {
            font-size: calc(14px + 0.2vw);
            background-color: #f8f9fa;
        }
        .onboard-card {
            border: none;
            border-radius: 12px;
        }
    </style>
</head>
<body class="py-5">
    <div class="container-fluid px-md-5">
        <div class="row justify-content-center">
            <div class="col-12 col-lg-8 col-xl-7">
                
                <?php if (!$isValid): ?>
                    <!-- Invalid Invitation Alert -->
                    <div class="card shadow-lg border-0 onboard-card p-4 text-center">
                        <div class="card-body">
                            <div class="d-inline-flex p-3 bg-danger bg-opacity-10 text-danger rounded-circle mb-3">
                                <i class="bi bi-envelope-exclamation fs-1"></i>
                            </div>
                            <h2 class="fw-bold text-dark">Access Denied</h2>
                            <p class="text-muted fs-6 mb-4"><?php echo htmlspecialchars($error); ?></p>
                            <div class="d-grid gap-2 col-sm-6 mx-auto">
                                <a href="login" class="btn btn-primary py-2 fw-bold">
                                    <i class="bi bi-arrow-left me-1"></i> Back to Login Page
                                </a>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- Onboarding Onboarding Form -->
                    <div class="card shadow-lg border-0 onboard-card p-4">
                        <div class="card-body">
                            <div class="text-center mb-4">
                                <div class="d-inline-flex p-3 bg-warning bg-opacity-10 text-warning-emphasis rounded-circle mb-3">
                                    <i class="bi bi-person-workspace fs-1"></i>
                                </div>
                                <h2 class="fw-bold">Speaker Onboarding</h2>
                                <p class="text-muted">Fill out your profile details to finalize your speaker account</p>
                            </div>

                            <?php if (!empty($error)): ?>
                                <div class="alert alert-danger shadow-sm border-0 mb-4" role="alert">
                                    <i class="bi bi-x-circle-fill me-2"></i>
                                    <?php echo htmlspecialchars($error); ?>
                                </div>
                            <?php endif; ?>

                            <form method="POST" action="onboard_speaker?token=<?php echo htmlspecialchars($token); ?>">
                                
                                <h5 class="fw-bold text-primary mb-3"><i class="bi bi-shield-lock-fill me-1"></i> Account Credentials</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-12 col-md-6">
                                        <label for="email" class="form-label">Email Address</label>
                                        <input type="email" class="form-control bg-light" id="email" readonly value="<?php echo htmlspecialchars($invitation['email']); ?>">
                                        <span class="small text-muted font-monospace">Linked to Invitation</span>
                                    </div>
                                    
                                    <div class="col-12 col-md-6">
                                        <label for="username" class="form-label">Username <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="username" name="username" required placeholder="e.g. janespeaker">
                                    </div>

                                    <div class="col-12">
                                        <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="password" name="password" required placeholder="••••••••">
                                    </div>
                                </div>

                                <h5 class="fw-bold text-primary mb-3"><i class="bi bi-person-vcard-fill me-1"></i> Speaker Profile Info</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-12 col-md-6">
                                        <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="full_name" name="full_name" required placeholder="e.g. Dr. Jane Speaker">
                                    </div>
                                    
                                    <div class="col-12 col-md-6">
                                        <label for="expertise" class="form-label">Area of Expertise <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="expertise" name="expertise" required placeholder="e.g. AI Research Lead / Tech Writer">
                                    </div>

                                    <div class="col-12">
                                        <label for="organization" class="form-label">Company / Organization</label>
                                        <input type="text" class="form-control" id="organization" name="organization" placeholder="e.g. AI Laboratories Inc.">
                                    </div>

                                    <div class="col-12">
                                        <label for="bio" class="form-label">Speaker Biography</label>
                                        <textarea class="form-control" id="bio" name="bio" rows="4" placeholder="Share a brief overview of your background, achievements, or session summaries..."></textarea>
                                    </div>
                                </div>

                                <div class="d-grid mb-2">
                                    <button type="submit" class="btn btn-success btn-lg py-2.5 fw-bold">
                                        <i class="bi bi-check2-circle me-1"></i> Complete Onboarding Profile
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
</body>
</html>
