<?php
// admin/save_games_ajax.php
session_start();
require '../includes/db.php'; 

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['status' => false, 'msg' => 'Access Denied']);
    exit;
}

// ইনপুট ডাটা নেওয়া
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (isset($data['games']) && is_array($data['games'])) {
    
    $provider_name = $data['provider_name'];
    $count = 0;

    $stmt = $conn->prepare("INSERT INTO games (game_uid, name, provider_id, image, category, status) VALUES (?, ?, ?, ?, ?, 'active') ON DUPLICATE KEY UPDATE name = VALUES(name), image = VALUES(image), provider_id = VALUES(provider_id)");

    foreach ($data['games'] as $game) {
        // সব ধরণের ফরম্যাট হ্যান্ডেল করা
        $g_uid = $game['game_code'] ?? $game['gameID'] ?? $game['id'] ?? $game['code'] ?? '';
        $g_name = $game['game_name'] ?? $game['gameNameEn'] ?? $game['name'] ?? $game['name_en'] ?? 'Unknown';
        $g_image = $game['game_img'] ?? $game['img'] ?? $game['icon'] ?? $game['img_url'] ?? '';
        $g_category = $game['category'] ?? $game['game_type'] ?? 'slots';

        if (!empty($g_uid)) {
            $stmt->bind_param("sssss", $g_uid, $g_name, $provider_name, $g_image, $g_category);
            if ($stmt->execute()) {
                $count++;
            }
        }
    }
    $stmt->close();
    echo json_encode(['status' => true, 'count' => $count]);
} else {
    echo json_encode(['status' => false, 'msg' => 'No games data received']);
}
?>