<?php
// File: login.php
// Handle user login

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

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

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

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Get user by email
    $stmt = $conn->prepare("
        SELECT id, email, user_name, password_hash, user_level, profile_picture, is_verified, is_deleted, created_at 
        FROM users 
        WHERE email = ?
    ");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        logActivity("Login attempt with non-existent email: $email");
        sendResponse(false, 'Invalid email or password');
    }
    
    if ($user['is_deleted'] == 1) {
        logActivity("Login attempt for deleted account: $email");
        sendResponse(false, 'This account has been deleted. Please contact support.');
    }
    
    if ($user['is_verified'] != 1) {
        logActivity("Login attempt with unverified email: $email");
        sendResponse(false, 'Please verify your email before logging in.');
    }
    
    if (!$user['user_name'] || !$user['password_hash']) {
        logActivity("Login attempt with incomplete registration: $email");
        sendResponse(false, 'Please complete your registration first.');
    }
    
    // Verify password
    if (!verifyPassword($password, $user['password_hash'])) {
        logActivity("Failed login attempt for: $email (wrong password)");
        sendResponse(false, 'Invalid email or password');
    }
    
    // Remove sensitive data
    unset($user['password_hash']);
    
    // Generate session token
    $token = generateSecureToken();
    
    // Get device info and IP
    $deviceInfo = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown Device';
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown IP';
    
    // ONE DEVICE AT A TIME: Delete all previous sessions for this user
    $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 token to user response
    $user['session_token'] = $token;
    $user['expires_at'] = $expiresAt;
    
    logActivity("Successful login: $email (Previous sessions terminated)");
    
    sendResponse(true, 'Login successful!', $user);
    
} catch (Exception $e) {
    logActivity("Login error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
