<?php
// Hata gösterimi
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include './database.php';

// API URL
$apiUrl = "https://api.veritral.com/public/api/gameplay/games";
$json = file_get_contents($apiUrl);
$data = json_decode($json, true);

$newCount = 0;
$existingCount = 0;
$newGames = []; // yeni eklenen oyunların isimlerini tutacak

// Transaction başlat
$pdo->beginTransaction();

foreach ($data['games'] as $game) {

    $id = $game['id'];

    // --- Var mı kontrolü (id üzerinden) ---
    $check = $pdo->prepare("SELECT COUNT(*) FROM games WHERE id = :id");
    $check->execute([':id' => $id]);
    if ($check->fetchColumn()) {
        $existingCount++;
        continue; // zaten varsa atla
    }

    // --- Yeni oyun verileri ---
    $game_id = $game['game_id'];
    $game_name = $game['title'];
    $game_code = $game['game_id'];
    $game_type = $game['type'];
    $description = isset($game['details']['tags']) ? implode(", ", $game['details']['tags']) : null;

    // Cover seçimi
    $thumbnails = $game['details']['thumbnails'] ?? [];
    $coverCandidates = ['300x300-TR','300x300','400x400','200x200','square','image','thumbnail'];
    $cover = null;
    foreach ($coverCandidates as $key) {
        if (!empty($thumbnails[$key])) {
            $cover = $thumbnails[$key];
            break;
        }
    }
    if (!$cover) {
        $cover = $game['details']['image'] ?? ($game['image'] ?? null);
    }
    $banner = $cover;

    // Platform bilgileri
    $technology = $game['platform'];
    $is_mobile = ($game['platform'] === 'desktop-and-mobile' || $game['platform'] === 'mobile') ? 1 : 0;
    $has_freespins = in_array('freespins', $game['details']['tags'] ?? []) ? 1 : 0;

    // Durum ve RTP
    $status = $game['enabled'] ? 1 : 0;
    $rtp = $game['details']['rtp'] ?? null;

    // Sağlayıcı dönüştürme
    $provider_name = $game['vendor'];
    $vendorMap = [
        'Pragmatic Play' => 'pragmatic',
        'EGT' => 'egtd',
        'EGT Digital' => 'egtdigital',
        'Popok' => 'popok',
        'Popok Gaming' => 'popok',
        '1x2 Gaming' => '1x2',
        'JVL' => 'jvl',
        'Fazi' => 'fazi',
        'Fils' => 'fils',
        '7777 Gaming' => '7777',
    ];
    $provider_game = $vendorMap[$provider_name] ?? strtolower(preg_replace('/[^a-z0-9]+/', '', $provider_name));
    $provider_code = $game_id;

    // Tarih alanları
    $created_at = isset($game['created_at']) ? date('Y-m-d H:i:s', strtotime($game['created_at'])) : date('Y-m-d H:i:s');
    $updated_at = isset($game['updated_at']) ? date('Y-m-d H:i:s', strtotime($game['updated_at'])) : date('Y-m-d H:i:s');

    // --- Ekleme işlemi ---
    $stmt = $pdo->prepare("
        INSERT INTO games 
        (id, game_id, game_name, game_code, game_type, description, cover, banner, technology, is_mobile, has_freespins, status, rtp, provider_game, provider_code, provider_name, created_at, updated_at)
        VALUES
        (:id, :game_id, :game_name, :game_code, :game_type, :description, :cover, :banner, :technology, :is_mobile, :has_freespins, :status, :rtp, :provider_game, :provider_code, :provider_name, :created_at, :updated_at)
    ");

    try {
        $stmt->execute([
            ':id' => $id,
            ':game_id' => $game_id,
            ':game_name' => $game_name,
            ':game_code' => $game_code,
            ':game_type' => $game_type,
            ':description' => $description,
            ':cover' => $cover,
            ':banner' => $banner,
            ':technology' => $technology,
            ':is_mobile' => $is_mobile,
            ':has_freespins' => $has_freespins,
            ':status' => $status,
            ':rtp' => $rtp,
            ':provider_game' => $provider_game,
            ':provider_code' => $provider_code,
            ':provider_name' => $provider_name,
            ':created_at' => $created_at,
            ':updated_at' => $updated_at
        ]);
        $newCount++;
        $newGames[] = $game_name;
    } catch (PDOException $e) {
        echo "Hata (id: $id): " . $e->getMessage() . "<br>";
    }
}

// Transaction’u bitir
$pdo->commit();

// --- Özet çıktısı ---
echo "<h3>Oyun Güncelleme Özeti</h3>";
echo "<p>Yeni eklenen oyun sayısı: <strong>$newCount</strong></p>";
echo "<p>Zaten veritabanında bulunan oyunlar: <strong>$existingCount</strong></p>";
echo "<p>Toplam işlenen oyun: <strong>" . ($newCount + $existingCount) . "</strong></p>";

if ($newCount > 0) {
    echo "<hr><h4>Yeni Eklenen Oyunlar:</h4><ul>";
    foreach ($newGames as $name) {
        echo "<li>" . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "</li>";
    }
    echo "</ul>";
} else {
    echo "<hr><p>Yeni eklenen oyun bulunmuyor.</p>";
}

echo "<hr><p>İşlem tamamlandı.</p>";
