<?php
/**
 * Login Endpoint v2
 * Handles user authentication with proper session and CORS handling
 */

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include required files
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';

// Set headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: same-origin');

// Initialize database connection
initAuth();

try {
    // Handle preflight OPTIONS request
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }

    // Only allow POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        header('Allow: POST');
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        exit;
    }

    // Get and validate input
    $input = json_decode(file_get_contents('php://input'), true);
    $username = trim($input['username'] ?? '');
    $password = $input['password'] ?? '';

    if (empty($username) || empty($password)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Username and password are required']);
        exit;
    }

    // Find user by username or email
    $stmt = $pdo->prepare("
        SELECT * FROM users 
        WHERE username = :username OR email = :email 
        LIMIT 1
    ");
    $stmt->execute([':username' => $username, ':email' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Log failed login attempt
    if (!$user) {
        error_log("Login failed: User not found - $username");
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid username or password']);
        exit;
    }

    // Verify password
    if (!password_verify($password, $user['password'])) {
        error_log("Login failed: Invalid password for user ID {$user['id']}");
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid username or password']);
        exit;
    }

    // Check if account is active
    if (isset($user['is_active']) && !$user['is_active']) {
        error_log("Login failed: Inactive account - User ID {$user['id']}");
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Account is inactive. Please contact support.']);
        exit;
    }

    // Check if email is verified if required
    if (isset($user['is_verified']) && !$user['is_verified']) {
        error_log("Login failed: Unverified email - User ID {$user['id']}");
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Please verify your email before logging in.']);
        exit;
    }

    // Login successful - set session variables
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['is_admin'] = !empty($user['is_admin']);
    $_SESSION['logged_in'] = true;
    $_SESSION['last_activity'] = time();
    
    // Regenerate session ID to prevent session fixation
    session_regenerate_id(true);

    // Log successful login
    error_log("Login successful - User ID: {$user['id']}, Username: {$user['username']}");

    // Return user data (without sensitive info)
    $userData = [
        'id' => $user['id'],
        'username' => $user['username'],
        'email' => $user['email'],
        'is_admin' => !empty($user['is_admin']),
        'session_timeout' => 1800 // 30 minutes
    ];

    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'user' => $userData
    ]);

} catch (PDOException $e) {
    error_log('Database error during login: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'A database error occurred. Please try again later.']);
} catch (Exception $e) {
    error_log('Error during login: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'An error occurred. Please try again.']);
}
