<?php

require_once 'pdo.php';

$casino_id = 29;
$name = 'bons';

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

// if ($isLocal) {

//     $url = 'https://fizzslots.com/data/v1/query';
//     $data = array(
//         'query' => '{"section":"casino","category":["slots"],"limit":60,"game_currency":"BRL","_xsrf":"2|f317c856|05db4c5006a00eb1ed273793f9bd1422|1704295579"}'
//     );

//     $data_string = json_encode($data);

//     $ch = curl_init($url);

//     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//     curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//         'Content-Type: application/json',
//         'Content-Length: ' . strlen($data_string)
//     ));

//     $result = curl_exec($ch);
//     curl_close($ch);

//     $file = $directory . '/gamble-free.com.parsing/casinos/'.$name.'.json';
//     file_put_contents($file, $result);

// } else {
    $file = $directory . '/gamble-free.com.parsing/casinos/'.$name.'.json';
// }

$games = json_decode(file_get_contents($file), true)['data']['casino']['slots'];

$insertedGames = [];

foreach ($games as $game) {
    $provider_name = $game['display_operator'];
    $game_name = $game['names']['en'];

    $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);
}

// curl -X POST 'https://fizzslots.com/data/v1/query' -d '{"query":"{\n        gamesByQuery (query: {name:\"\",, pageable: {page: 0,size: 10000}}) {\n            id,\n            name,\n            vendorId,\n            categoryIds,\n            tags {\n                name\n            },\n            images {\n                type,\n                path\n            },\n            isFavourite\n        }\n    }"}'

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