<?php

require_once 'pdo.php';

$casino_id = 21;
$name = 'winz';

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

if ($isLocal) {

    $url = 'https://dlxcasino.com/api/games/allowed_desktop';

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Referer: https://winz.io/'
    ));

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

$insertedGames = [];

foreach ($games as $game) {
    $provider_name = $game["provider"];
    $game_name = $game['title'];

    $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 GET 'https://dlxcasino.com/api/games/allowed_desktop' -H 'Referer: https://winz.io/'

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