<?php
ob_start();
try {
    require_once __DIR__ . '/../../includes/auth.php';
} catch (Throwable $e) {
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode(['success'=>false,'error'=>'Server error']);
    exit;
}
ob_end_clean();
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success'=>false,'error'=>'Method not allowed']); exit;
}

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

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

try {
    $result = loginUser($username, $password);
} catch (Throwable $e) {
    echo json_encode(['success'=>false,'error'=>'Login error. Please try again.']); exit;
}

if ($result['success'] && isset($result['user'])) {
    logPlayerAction('LOGIN_SUCCESS', $result['user']['id'], 'User logged in', 'auth', 'info');
    unset($result['user']['password']);
}
if (!$result['success']) { logSecurityEvent('LOGIN_FAILED', null, 'Failed login attempt for: ' . $username, 'warning'); }
echo json_encode($result);
