<?php
// File: complete_registration.php
// Complete registration with username and password after email verification

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';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1');
define('ALLOWED_USER_AGENTS', [
    'Dart/',
    'ensi-flutter-app',
]);

// Helper: Validate API access
function validateApiAccess() {
    $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;
    }
    
    $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;
    }
    
    error_log("Complete Registration API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

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']) || empty($input['user_name']) || empty($input['password'])) {
    sendResponse(false, 'Email, username, and password are required');
}

$email = sanitizeInput($input['email']);
$userName = sanitizeInput($input['user_name']);
$password = $input['password']; // Don't sanitize password

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

// Validate username
if (strlen($userName) < 3) {
    sendResponse(false, 'Username must be at least 3 characters');
}

if (!preg_match('/^[a-zA-Z0-9_]+$/', $userName)) {
    sendResponse(false, 'Username can only contain letters, numbers, and underscore');
}

// Validate password
if (strlen($password) < 6) {
    sendResponse(false, 'Password must be at least 6 characters');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if email is verified
    $stmt = $conn->prepare("SELECT id, is_verified, is_deleted, user_name FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        sendResponse(false, 'User not found. Please register first.');
    }
    
    if ($user['is_deleted'] == 1) {
        sendResponse(false, 'This account has been deleted.');
    }
    
    if ($user['is_verified'] != 1) {
        sendResponse(false, 'Please verify your email first.');
    }
    
    if ($user['user_name']) {
        sendResponse(false, 'Registration already completed. Please login.');
    }
    
    // Check if username is already taken
    $stmt = $conn->prepare("SELECT id FROM users WHERE user_name = ? AND id != ?");
    $stmt->execute([$userName, $user['id']]);
    if ($stmt->fetch()) {
        sendResponse(false, 'Username already taken. Please choose another.');
    }
    
    // Hash password
    $passwordHash = hashPassword($password);
    
    // Generate profile picture URL
    $profilePicture = "https://api.dicebear.com/7.x/fun-emoji/jpg?seed=" . urlencode($email);
    
    // Update user with username and password
    $stmt = $conn->prepare("
        UPDATE users 
        SET user_name = ?, 
            password_hash = ?, 
            profile_picture = ?,
            user_level = 'registered',
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$userName, $passwordHash, $profilePicture, $user['id']]);
    
    // Get updated user data
    $stmt = $conn->prepare("
        SELECT id, email, user_name, user_level, profile_picture, is_verified, created_at 
        FROM users 
        WHERE id = ?
    ");
    $stmt->execute([$user['id']]);
    $userData = $stmt->fetch();
    
    // Generate session token and log the user in automatically
    $token = generateSecureToken();
    
    // Get device info and IP
    $deviceInfo = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown Device';
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown IP';
    
    // Delete any previous sessions for this user (one device at a time)
    $stmt = $conn->prepare("DELETE FROM user_sessions WHERE user_id = ?");
    $stmt->execute([$user['id']]);
    
    // Set expiry (30 days)
    $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    // Save new session to database
    $stmt = $conn->prepare("
        INSERT INTO user_sessions (user_id, token, device_info, ip_address, expires_at) 
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([$user['id'], $token, $deviceInfo, $ipAddress, $expiresAt]);
    
    // Add session token to response
    $userData['session_token'] = $token;
    $userData['expires_at'] = $expiresAt;
    
    logActivity("Registration completed and auto-login successful for: $email (Username: $userName)");
    
    sendResponse(true, 'Registration completed successfully! You are now logged in.', $userData);
    
} catch (Exception $e) {
    logActivity("Complete registration error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
