<?php

require_once 'pdo.php';

$casino_id = 19;
$name = 'lalabet';

$isLocal = getenv('LOCAL_ENV') === 'true';
$directory = $isLocal ? "/Users/serhiipozynich" : "/var/www";

if ($isLocal) {
    $url = 'https://lala.bet/api/games/list';
    $data = array(
        'component' => 'games.tGameCatalog.list',
        'query' => array(
            'categoryIds' => [],
            'providerIds' => [],
            'name' => '',
            'limit' => 24,
            'isEnabledGeoRestricts' => false,
            'hasDesktop' => true,
            'partition' => 'casino',
        ),
    );

    $data_string = json_encode($data);

    // Initialize an empty array to store all games
    $allGames = [];

    $offset = 0;
    $limit = 24;

    while (true) {
        // Add the current offset to the query
        $data['query']['offset'] = $offset;
        $data_string = json_encode($data);

        // Execute the curl command and capture the result
        $command = "curl -X POST '$url' -d '$data_string' -H 'Content-Type: application/json' | jq '.data.list'";
        $result = shell_exec($command);

        // Decode the JSON result and append it to the allGames array
        $games = json_decode($result, true);
        if (empty($games)) {
            // No more data, break the loop
            break;
        }
        $allGames = array_merge($allGames, $games);

        // Increment the offset
        $offset += $limit;
    }

    // Save the result to the file
    $file = $directory . '/gamble-free.com.parsing/casinos/' . $name . '.json';
    file_put_contents($file, json_encode($allGames));
} else {
    $file = $directory . '/gamble-free.com.parsing/casinos/' . $name . '.json';
}

$games = json_decode(file_get_contents($file), true);

$insertedGames = [];

foreach ($games as $game) {
    $provider_name = $game['providerName'];
    $game_name = $game['name'];

    $insertQuery = "INSERT INTO casinos_games (casino_id, game_name, provider_name)
        VALUES (:casino_id, :game_name, :provider_name) ON DUPLICATE KEY UPDATE casino_id = VALUES(casino_id)";

    $stmt = $db->prepare($insertQuery);
    $stmt->bindParam(':casino_id', $casino_id, PDO::PARAM_INT);
    $stmt->bindParam(':game_name', $game_name, PDO::PARAM_STR);
    $stmt->bindParam(':provider_name', $provider_name, PDO::PARAM_STR);
    $stmt->execute();

    $insertedGames[] = array(
        'game_name' => $game_name,
        'provider_name' => $provider_name,
    );

    $count = count($insertedGames);
}

echo json_encode(['insertedGames' => $insertedGames, 'count' => $count], JSON_PRETTY_PRINT);
?>
