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

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

if (isset($_POST['brand_id']) && isset($_POST['brand_name'])) {
    
    $brand_id = $_POST['brand_id'];
    $brand_name = $_POST['brand_name'];
    
    // API URL
    $api_url = "https://igamingapis.com/provider/brands.php?brand_id=" . urlencode($brand_id);
    
    // CURL Setup (User Agent সহ)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if(curl_errno($ch)){
        echo json_encode(['status' => false, 'msg' => 'Curl Error']);
        exit;
    }
    curl_close($ch);

    // JSON Decode
    $data = json_decode($response, true);
    
    // ডাটা ভ্যালিডেশন
    if (!isset($data['games']) || !is_array($data['games'])) {
        // কিছু ব্র্যান্ডে গেম নাও থাকতে পারে, সেটা এরর না
        echo json_encode(['status' => false, 'msg' => 'No games found (or API blocked)']);
        exit;
    }

    $count = 0;
    
    // SQL Prepared Statement for Speed & Safety
    $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, $brand_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' => 'Invalid Request']);
}
?>