<?php
$host = 'localhost';
$dbname = 'blacrhdy_bet1';
$user = 'blacrhdy_bet1';
$pass = 'blacrhdy_bet1';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Veritabanı bağlantı hatası: ' . $e->getMessage();
    exit;
}

// Arama terimi parametresini al
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';

if (empty($searchTerm)) {
    echo json_encode(['success' => false, 'message' => 'Arama terimi boş']);
    exit;
}

// Güvenlik için arama terimini temizle
$searchTerm = '%' . $searchTerm . '%';

try {
    // Tüm slot oyunlarında arama yap
    $sql = "SELECT game_id, game_name, cover, game_type, provider_game FROM games 
            WHERE LOWER(game_type) LIKE 'slot%' 
            AND LOWER(game_name) LIKE LOWER(:search_term) 
            ORDER BY game_name ASC 
            LIMIT 100";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':search_term', $searchTerm, PDO::PARAM_STR);
    $stmt->execute();
    $games = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($games)) {
        echo json_encode(['success' => false, 'message' => 'Arama sonucu bulunamadı']);
        exit;
    }

    // Oyunları HTML olarak oluştur
    $html = '<div class="game-grid">';
    
    foreach ($games as $game) {
        $gameId = htmlspecialchars($game['game_id']);
        $gameName = htmlspecialchars($game['game_name']);
        $cover = htmlspecialchars($game['cover']);
        $provider = htmlspecialchars($game['provider_game']);
        
        $html .= '<div class="game-item" data-provider="' . $provider . '">';
        $html .= '<img src="' . $cover . '" alt="' . $gameName . '" onclick="window.open(\'/start/game.php?gameid=' . $gameId . '\', \'_blank\')">';
        $html .= '<div class="game-actions">';
        $html .= '<button class="btn-real" onclick="window.open(\'/start/game.php?gameid=' . $gameId . '\', \'_blank\')">Oyna</button>';
        $html .= '<button class="btn-demo" onclick="window.open(\'/start/game.php?gameid=' . $gameId . '&demo=1\', \'_blank\')">Demo</button>';
        $html .= '</div>';
        $html .= '<p>' . $gameName . '</p>';
        $html .= '</div>';
    }
    
    $html .= '</div>';

    // JSON yanıtı döndür
    echo json_encode([
        'success' => true,
        'html' => $html,
        'count' => count($games)
    ]);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Veritabanı hatası: ' . $e->getMessage()]);
}
?>