<?php
/**
 * Secure User Registration API
 * Enhanced with comprehensive input validation and security measures
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, User-Agent');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';
require_once 'enhanced_security.php';
require_once 'send_email.php';

// Validate API access with enhanced security
validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendSecureResponse(false, 'Method not allowed', null, 405);
}

// Get and validate JSON input
$rawInput = file_get_contents('php://input');
if (empty($rawInput)) {
    sendSecureResponse(false, 'No input data provided', null, 400);
}

$input = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    sendSecureResponse(false, 'Invalid JSON format', null, 400);
}

try {
    // Validate required fields
    if (empty($input['email'])) {
        sendSecureResponse(false, 'Email is required', null, 400);
    }
    
    if (empty($input['username'])) {
        sendSecureResponse(false, 'Username is required', null, 400);
    }
    
    if (empty($input['password'])) {
        sendSecureResponse(false, 'Password is required', null, 400);
    }
    
    // Validate and sanitize inputs using enhanced security
    $email = SecurityValidator::validateEmail($input['email']);
    $username = SecurityValidator::validateUsername($input['username']);
    $password = SecurityValidator::validatePassword($input['password']);
    
    // Optional: Validate display name if provided
    $displayName = null;
    if (!empty($input['display_name'])) {
        $displayName = SecurityValidator::validateText($input['display_name'], SecurityValidator::MAX_NAME_LENGTH);
    }
    
    // Database operations with prepared statements
    $conn = getDBConnection();
    if (!$conn) {
        sendSecureResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if email already exists
    $stmt = $conn->prepare("SELECT id, is_verified, is_deleted FROM users WHERE email = ?");
    if (!$stmt) {
        error_log("Database prepare error: " . $conn->errorInfo()[2]);
        sendSecureResponse(false, 'Database error occurred', null, 500);
    }
    
    $stmt->execute([$email]);
    $existingUser = $stmt->fetch();
    
    if ($existingUser) {
        if ($existingUser['is_deleted'] == 1) {
            sendSecureResponse(false, 'This account has been deleted. Please contact support.', null, 403);
        }
        
        if ($existingUser['is_verified'] == 1) {
            sendSecureResponse(false, 'An account with this email already exists', null, 409);
        } else {
            // User exists but not verified, allow resending verification
            sendSecureResponse(true, 'Verification email has been resent. Please check your inbox.');
        }
    }
    
    // Check if username already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE user_name = ? AND is_deleted = 0");
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        sendSecureResponse(false, 'Username is already taken', null, 409);
    }
    
    // Generate secure verification code
    $verificationCode = sprintf('%04d', random_int(1000, 9999));
    $codeExpiry = date('Y-m-d H:i:s', time() + (15 * 60)); // 15 minutes
    
    // Hash password securely
    $passwordHash = SecurityValidator::hashPassword($password);
    
    // Begin transaction
    $conn->beginTransaction();
    
    try {
        // Insert or update user
        if ($existingUser) {
            // Update existing unverified user
            $stmt = $conn->prepare("
                UPDATE users 
                SET user_name = ?, password_hash = ?, updated_at = CURRENT_TIMESTAMP 
                WHERE email = ?
            ");
            $stmt->execute([$username, $passwordHash, $email]);
            $userId = $existingUser['id'];
        } else {
            // Create new user
            $stmt = $conn->prepare("
                INSERT INTO users (email, user_name, password_hash, user_level, is_verified, created_at, updated_at) 
                VALUES (?, ?, ?, 'registered', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            ");
            $stmt->execute([$email, $username, $passwordHash]);
            $userId = $conn->lastInsertId();
        }
        
        // Clear any existing verification codes for this email
        $stmt = $conn->prepare("
            UPDATE verification_codes 
            SET is_used = 1 
            WHERE email = ? AND purpose = 'registration' AND is_used = 0
        ");
        $stmt->execute([$email]);
        
        // Insert new verification code
        $stmt = $conn->prepare("
            INSERT INTO verification_codes (email, code, purpose, expires_at, created_at) 
            VALUES (?, ?, 'registration', ?, CURRENT_TIMESTAMP)
        ");
        $stmt->execute([$email, $verificationCode, $codeExpiry]);
        
        // Commit transaction
        $conn->commit();
        
        // Send verification email
        $subject = "Verify your ENSI.LK account";
        $bodyHTML = "
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset='UTF-8'>
                <style>
                    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                    .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
                    .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                    .code { background: #4CAF50; color: white; padding: 15px 30px; font-size: 24px; font-weight: bold; text-align: center; border-radius: 5px; margin: 20px 0; letter-spacing: 3px; }
                    .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h1>Welcome to ENSI.LK!</h1>
                        <p>Master English with Fun</p>
                    </div>
                    <div class='content'>
                        <h2>Email Verification Required</h2>
                        <p>Hello <strong>" . htmlspecialchars($username) . "</strong>,</p>
                        <p>Thank you for registering with ENSI.LK! To complete your registration, please use the verification code below:</p>
                        <div class='code'>{$verificationCode}</div>
                        <p><strong>This code will expire in 15 minutes.</strong></p>
                        <p>If you didn't create this account, please ignore this email.</p>
                        <p>For security reasons, never share this code with anyone.</p>
                    </div>
                    <div class='footer'>
                        <p>&copy; 2025 ENSI.LK - Your English Learning Journey Starts Here!</p>
                    </div>
                </div>
            </body>
            </html>
        ";
        
        $emailSent = sendIdeasEmail($email, $subject, $bodyHTML);
        
        if ($emailSent) {
            // Log successful registration
            error_log("Registration successful for email: $email, username: $username");
            
            sendSecureResponse(true, 'Registration successful! Please check your email for the verification code.', [
                'user_id' => $userId,
                'email' => $email,
                'username' => $username,
                'requires_verification' => true
            ]);
        } else {
            // Rollback if email failed
            $conn->rollback();
            error_log("Failed to send verification email for: $email");
            sendSecureResponse(false, 'Failed to send verification email. Please try again later.', null, 500);
        }
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        error_log("Registration transaction error: " . $e->getMessage());
        sendSecureResponse(false, 'Registration failed. Please try again.', null, 500);
    }
    
} catch (InvalidArgumentException $e) {
    // Handle validation errors
    error_log("Registration validation error: " . $e->getMessage());
    sendSecureResponse(false, $e->getMessage(), null, 400);
    
} catch (Exception $e) {
    // Handle unexpected errors
    error_log("Registration unexpected error: " . $e->getMessage());
    sendSecureResponse(false, 'An unexpected error occurred. Please try again later.', null, 500);
}
?>