<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'invitation' => null
];

$role = $_GET['role'] ?? $_POST['role'] ?? 'speaker';
$token = trim($_GET['token'] ?? $_POST['token'] ?? '');

if (empty($token)) {
    $response['message'] = "Invitation token is required.";
    echo json_encode($response);
    exit();
}

$role_to_table = [
    'speaker'  => 'speaker_invitations',
    'organizer' => 'organizer_invitations',
    'sponsor'  => 'sponsor_invitations'
];
if (!isset($role_to_table[$role])) {
    $response['message'] = "Invalid role.";
    echo json_encode($response);
    exit();
}
$table = $role_to_table[$role];

// 1. Verify token
try {
    $stmt = $pdo->prepare("SELECT * FROM {$table} WHERE token = ? AND status = 'pending'");
    $stmt->execute([$token]);
    $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$invitation) {
        $response['message'] = "This invitation token is invalid or has already been used.";
        echo json_encode($response);
        exit();
    }
    $response['invitation'] = $invitation;
} catch (PDOException $e) {
    $response['message'] = "Verification failed.";
    echo json_encode($response);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Perform registration
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $response['message'] = "Username and password are required.";
        echo json_encode($response);
        exit();
    }
    if (strlen($password) < 8) {
        $response['message'] = "Password must be at least 8 characters long.";
        echo json_encode($response);
        exit();
    }

    try {
        $pdo->beginTransaction();

        // Check if username/email already taken
        $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
        $check->execute([$username, $invitation['email']]);
        if ($check->fetchColumn() > 0) {
            $response['message'] = "Username or Email already exists.";
            $pdo->rollBack();
            echo json_encode($response);
            exit();
        }

        // Crypto-safe employee code generation with uniqueness check
        $emp_code = '';
        $attempts = 0;
        while ($attempts < 20) {
            $candidate = 'REPL' . strtoupper(bin2hex(random_bytes(3)));
            $chk = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
            $chk->execute([$candidate]);
            if ((int)$chk->fetchColumn() === 0) {
                $emp_code = $candidate;
                break;
            }
            $attempts++;
        }
        if (empty($emp_code)) {
            $pdo->rollBack();
            $response['message'] = "Failed to generate a unique employee code. Please try again.";
            echo json_encode($response);
            exit();
        }
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        
        $ins = $pdo->prepare("INSERT INTO users (username, email, password, role, status, employee_code) VALUES (?, ?, ?, ?, 'active', ?)");
        $ins->execute([$username, $invitation['email'], $hashed, $role, $emp_code]);
        $user_id = $pdo->lastInsertId();

        // Insert profile FIRST — then award bonuses after, so a profile failure rolls back everything
        if ($role === 'speaker') {
            $full_name = trim($_POST['full_name'] ?? '');
            $expertise = trim($_POST['expertise'] ?? '');
            $organization = trim($_POST['organization'] ?? '');
            $bio = trim($_POST['bio'] ?? '');
            $ins_p = $pdo->prepare("INSERT INTO speaker_profiles (user_id, full_name, expertise, organization, bio) VALUES (?, ?, ?, ?, ?)");
            $ins_p->execute([$user_id, $full_name, $expertise, $organization, $bio]);
        } elseif ($role === 'organizer') {
            $full_name = trim($_POST['full_name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $company = trim($_POST['company'] ?? '');
            $department = trim($_POST['department'] ?? '');
            $ins_p = $pdo->prepare("INSERT INTO organizer_profiles (user_id, full_name, phone, company, department) VALUES (?, ?, ?, ?, ?)");
            $ins_p->execute([$user_id, $full_name, $phone, $company, $department]);
        } elseif ($role === 'sponsor') {
            $company_name = trim($_POST['company_name'] ?? '');
            $website_url = trim($_POST['website_url'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $ins_p = $pdo->prepare("INSERT INTO sponsor_profiles (user_id, company_name, website_url, description) VALUES (?, ?, ?, ?)");
            $ins_p->execute([$user_id, $company_name, $website_url, $description]);
        }

        // Award bonuses inside the transaction — after profile insert succeeds
        require_once __DIR__ . '/../../includes/bonus_helper.php';
        awardSignupAndReferralBonuses($user_id);

        // Mark invitation as accepted
        $upd_inv = $pdo->prepare("UPDATE {$table} SET status = 'accepted' WHERE id = ?");
        $upd_inv->execute([$invitation['id']]);

        $pdo->commit();
        
        $response['success'] = true;
        $response['message'] = "Onboarding completed successfully! Please log in.";
        $response['redirect'] = 'login.php';
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log("Onboard error: " . $e->getMessage());
        $response['message'] = "Onboarding failed. Please try again.";
    }
} else {
    $response['success'] = true;
}

echo json_encode($response);
