<?php
require_once '../config.php';

// Enforce Rate Limiting (Max 5 signups per minute per IP)
checkRateLimit('signup', 5, 60);

$data = json_decode(file_get_contents("php://input"), true);

if (empty($data['full_name']) || empty($data['email']) || empty($data['phone']) || empty($data['password'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "All fields (full_name, email, phone, password) are required."]);
    exit();
}

// Sanitize inputs
$fullName = sanitizeInput($data['full_name']);
$email = filter_var($data['email'], FILTER_SANITIZE_EMAIL);
$phone = sanitizeInput($data['phone']);
$password = $data['password'];

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Please provide a valid email address."]);
    exit();
}

// Anti-Fraud Referral Checks
$referralCode = isset($data['referral_code']) ? sanitizeInput($data['referral_code']) : '';
if (!empty($referralCode)) {
    if (strtolower(trim($referralCode)) === strtolower(trim($email)) || strtolower(trim($referralCode)) === strtolower(trim($phone))) {
        logSecurityError("Blocked Referral - Self-referral attempt by $email");
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Anti-Fraud Policy: You cannot refer yourself."]);
        exit();
    }
}

try {
    $db = getDBConnection();

    // Check if email already registered
    $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(["status" => "error", "message" => "An account with this email address already exists."]);
        exit();
    }

    // Hash password securely (2026 bcrypt standard)
    $password_hash = password_hash($password, PASSWORD_BCRYPT);

    // Start a transaction
    $db->beginTransaction();

    // Insert user
    $stmt = $db->prepare("INSERT INTO users (full_name, email, phone, password_hash, is_verified, referred_by) VALUES (?, ?, ?, ?, 0, ?)");
    $stmt->execute([$fullName, $email, $phone, $password_hash, !empty($referralCode) ? $referralCode : null]);
    
    // Generate a 6-digit OTP code
    $otp_code = strval(rand(100000, 999999));
    $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    // Insert OTP code
    $stmt = $db->prepare("INSERT INTO user_otps (email, code, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$email, $otp_code, $expires_at]);

    $db->commit();

    // Dispatch premium HTML verification email
    $emailSubject = "Verify Your Think Rich Naija Account";
    $emailBody = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 10px;'>
            <div style='text-align: center; margin-bottom: 20px;'>
                <h1 style='color: #009247; margin: 0;'>Think Rich Naija</h1>
            </div>
            <h2 style='color: #2d3748;'>Welcome to the Cash Trivia Arena, " . htmlspecialchars($fullName) . "!</h2>
            <p style='color: #4a5568; line-height: 1.6;'>Thank you for registering. To activate your account and start competing, please verify your email address by entering the 6-digit OTP code below:</p>
            <div style='background-color: #f7fafc; padding: 15px; text-align: center; border-radius: 8px; margin: 24px 0;'>
                <span style='font-size: 32px; font-weight: bold; letter-spacing: 6px; color: #009247;'>" . $otp_code . "</span>
            </div>
            <p style='color: #718096; font-size: 12px; line-height: 1.4;'>This OTP code is valid for exactly 10 minutes. If you did not register for this account, please ignore this email or contact support.</p>
            <div style='border-top: 1px solid #edf2f7; margin-top: 24px; padding-top: 16px; text-align: center; color: #a0aec0; font-size: 11px;'>
                &copy; " . date('Y') . " Think Rich Naija. All rights reserved.
            </div>
        </div>
    ";
    
    sendEmail($email, $emailSubject, $emailBody);

    echo json_encode([
        "status" => "success",
        "message" => "Account created successfully! Enter the verification code sent to your email.",
        "email" => $email,
        "debug_otp" => $otp_code
    ]);

} catch(PDOException $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    logSecurityError("Signup Execution Failure: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Registration failed. Please contact support."]);
}
?>
