<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json');

try {
    require_once '../db.php';

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Méthode non autorisée.']);
        exit;
    }

    $data = json_decode(file_get_contents('php://input'), true);

    $identifier = trim($data['identifier'] ?? '');
    $password = $data['password'] ?? '';

    if (empty($identifier) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Identifiant et mot de passe requis.']);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT u.id, u.username, u.email, u.password_hash, s.level, s.current_xp, s.health_points, s.companion_state 
        FROM users u 
        LEFT JOIN user_stats s ON u.id = s.user_id 
        WHERE u.email = :identifier OR u.username = :identifier
    ");
    $stmt->execute(['identifier' => $identifier]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];

        echo json_encode([
            'success' => true,
            'message' => 'Connexion réussie !',
            'user' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'stats' => [
                    'level' => (int)($user['level'] ?? 1),
                    'current_xp' => (int)($user['current_xp'] ?? 0),
                    'health_points' => (int)($user['health_points'] ?? 100),
                    'companion_state' => $user['companion_state'] ?? 'happy'
                ]
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Identifiant ou mot de passe incorrect.']);
    }

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur serveur : ' . $e->getMessage()]);
}
?>