<?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['provider'], $data['email'], $data['firebase_uid'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required data"]);
    exit;
}

$provider = $data['provider'];
$name = $data['name'] ?? '';
$email = $data['email'];
$firebaseUid = $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 {
    // 🔹 1. Adım: Email ile kayıtlı kullanıcı var mı?
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existingUser) {
        // 🔹 Email varsa firebase_uid güncellenir (anonimden gelmiş olabilir)
        $stmt = $pdo->prepare("UPDATE users SET firebase_uid = ?, login_provider = ? WHERE email = ?");
        $stmt->execute([$firebaseUid, $provider, $email]);

        $userId = $existingUser['id'];
    } else {
        // 🔹 2. Adım: firebase_uid ile eşleşen anonim kullanıcı var mı?
        $stmt = $pdo->prepare("SELECT * FROM users WHERE firebase_uid = ? AND email IS NULL");
        $stmt->execute([$firebaseUid]);
        $anonUser = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($anonUser) {
            // 🔹 Mevcut anonim kullanıcıyı güncelle
            $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, login_provider = ? WHERE id = ?");
            $stmt->execute([$name, $email, $provider, $anonUser['id']]);
            $userId = $anonUser['id'];
        } else {
            // 🔹 3. Adım: Yeni kullanıcı oluştur
            $nickname = generateUniqueNickname($pdo);
            $createdAt = date('Y-m-d H:i:s');
            $credits = 0;
            $points = 0;

            $stmt = $pdo->prepare("INSERT INTO users (name, email, login_provider, credits, nickname, firebase_uid, created_at, points) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $email, $provider, $credits, $nickname, $firebaseUid, $createdAt, $points]);
            $userId = $pdo->lastInsertId();
        }
    }

    // 🔹 Son kullanıcıyı al
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // 🔹 JWT token oluştur
    $payload = [
        'sub' => $user['id'],
        'email' => $user['email'],
        'iat' => time(),
        'exp' => time() + 60 * 60 * 24 * 720 // 2 yıl geçerli
    ];

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

    echo json_encode([
        "success" => true,
        "token" => $jwt,
        "user" => [
            "id" => $user['id'],
            "name" => $user['name'],
            "email" => $user['email'],
            "credits" => $user['credits'],
            "nickname" => $user['nickname']
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Server error", "details" => $e->getMessage()]);
    exit;
}