<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->email) || !isset($data->password)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing email or password']);
    exit;
}

$email = trim($data->email);
$password = $data->password;

try {
    // Correct table 'i_users' for independent KLKAPP TEST
    $stmt = $pdo->prepare("SELECT * FROM i_users WHERE i_user_email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['i_password'])) {
        
        // Use 'iuid' for token generation
        $token = Auth::generateToken($user['iuid']);

        unset($user['i_password']); // Do not return hash

        // Map for frontend consistency
        $frontendUser = [
            'id' => $user['iuid'],
            'username' => $user['i_username'],
            'email' => $user['i_user_email'],
            'avatar' => $user['user_avatar'] ?? 'default.png',
            'level' => $user['level'] ?? 1,
            'xp' => $user['xp'] ?? 0,
            'diamonds' => $user['diamonds'] ?? 0
        ];

        echo json_encode([
            'message' => 'Login successful',
            'token' => $token,
            'user' => $frontendUser
        ]);
    } else {
        http_response_code(401);
        echo json_encode(['error' => 'invalid_credentials']);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'DB Error: ' . $e->getMessage()]);
}
?>
