<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once '/home/akgbilis/fi_sf/config.php';
use Firebase\JWT\JWT;

$env = require '/home/akgbilis/fi_sf/.env.php';

header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"), true);

// 🔸 Gerekli alanlar kontrolü
if (!isset($data['firebase_uid'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing firebase_uid"]);
    exit;
}

$firebase_uid = $data['firebase_uid'];

// 🔸 Nickname üretici fonksiyon
function generateUniqueNickname(PDO $pdo): string {
    $base = "BetsAI";
    $number = 100;

    while (true) {
        $nickname = $base . $number;
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE nickname = ?");
        $stmt->execute([$nickname]);
        if ($stmt->fetchColumn() == 0) {
            return $nickname;
        }
        $number++;
    }
}

try {
    // 🔸 Zaten kayıtlı mı?
    $stmt = $pdo->prepare("SELECT * FROM users WHERE firebase_uid = ?");
    $stmt->execute([$firebase_uid]);
    $user = $stmt->fetch();

    if (!$user) {
        // 🔸 Yeni kullanıcı oluşturuluyor
        $nickname = generateUniqueNickname($pdo);
        $stmt = $pdo->prepare("INSERT INTO users (firebase_uid, credits, nickname) VALUES (?, 0, ?)");
        $stmt->execute([$firebase_uid, $nickname]);

        $userId = $pdo->lastInsertId();

        // 🔄 Yeni kullanıcıyı çek
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();

        if (!$user) {
            throw new Exception("User creation failed");
        }
    }

    // 🔐 JWT oluştur
    $payload = [
        'sub' => $user['id'],
        'uid' => $user['firebase_uid'],
        'iat' => time(),
        'exp' => time() + 60 * 60 * 24 * 720
    ];

    $jwt = JWT::encode($payload, $env['jwt_secret'], 'HS256');

    // 🔁 JSON yanıt
    echo json_encode([
        "success" => true,
        "token" => $jwt,
        "user" => [
            "id" => $user['id'],
            "firebase_uid" => $user['firebase_uid'],
            "credits" => $user['credits'],
            "nickname" => $user['nickname']
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Server error", "details" => $e->getMessage()]);
    exit;
}