<?php
// File: register.php
// Handle user registration - Step 1: Send verification code

header('Content-Type: application/json');
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 'send_email.php';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1'); // Must match lesson_service.dart
define('ALLOWED_USER_AGENTS', [
    'Dart/', // Flutter/Dart HTTP client
    'ensi-flutter-app', // Custom user agent for your app
]);

// Helper: Validate API access
function validateApiAccess() {
    // Check API Key
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    // Check User Agent
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    // Log access attempts
    error_log("Register API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

// Validate API access before processing any requests
validateApiAccess();

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

$input = getJsonInput();

// Validate input
if (empty($input['email'])) {
    sendResponse(false, 'Email is required');
}

$email = sanitizeInput($input['email']);

// Validate email format
if (!validateEmail($email)) {
    sendResponse(false, 'Invalid email format');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if user already exists and is verified
    $stmt = $conn->prepare("SELECT id, is_verified, is_deleted FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $existingUser = $stmt->fetch();
    
    if ($existingUser) {
        if ($existingUser['is_deleted'] == 1) {
            sendResponse(false, 'This account has been deleted. Please contact support.');
        }
        
        if ($existingUser['is_verified'] == 1) {
            sendResponse(false, 'Email already registered. Please login.');
        }
        
        // User exists but not verified - allow resend
        logActivity("Resending verification code for existing unverified user: $email");
    } else {
        // Create new user entry
        $stmt = $conn->prepare("INSERT INTO users (email, is_verified) VALUES (?, 0)");
        $stmt->execute([$email]);
        logActivity("New user registration started: $email");
    }
    
    // Generate verification code
    $code = generateVerificationCode();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));
    
    // Delete old unused codes for this email
    $stmt = $conn->prepare("DELETE FROM verification_codes 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) VALUES (?, ?, 'registration', ?)");
    $stmt->execute([$email, $code, $expiresAt]);
    
    // Send email
    $subject = "ensi.lk - Email Verification Code";
    $bodyHTML = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #6C63FF 0%, #FF6584 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px; }
                .code { font-size: 32px; font-weight: bold; color: #6C63FF; text-align: center; letter-spacing: 10px; padding: 20px; background: white; border-radius: 10px; margin: 20px 0; }
                .footer { text-align: center; color: #636E72; padding: 20px; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Welcome to ensi.lk! 🎓</h1>
                    <p>Your English Learning Journey Starts Here</p>
                </div>
                <div class='content'>
                    <h2>Email Verification</h2>
                    <p>Thank you for registering! Please use the following verification code to complete your registration:</p>
                    <div class='code'>$code</div>
                    <p><strong>This code will expire in 15 minutes.</strong></p>
                    <p>If you didn't request this code, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 ensi.lk - Master English with Fun!</p>
                </div>
            </div>
        </body>
        </html>
    ";
    
    $emailSent = sendIdeasEmail($email, $subject, $bodyHTML);
    
    if ($emailSent) {
        logActivity("Verification code sent successfully to: $email");
        sendResponse(true, 'Verification code sent to your email. Please check your inbox.');
    } else {
        logActivity("Failed to send verification email to: $email");
        sendResponse(false, 'Failed to send verification email. Please try again later.', null, 500);
    }
    
} catch (Exception $e) {
    logActivity("Registration error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
