<?php

$casino_id = 5;
$name = 'dlx';

$isLocal = getenv('LOCAL_ENV') === 'true';
$isParsing = getenv('PARSING_ENV') === 'true';
$isProd = getenv('PROD_ENV') === 'true';

$directory = $isLocal ? "/Users/serhiipozynich" : "/var/www";

$proxyHost = '';
$proxyPort = '';

// Parse command line arguments
$args = getopt(null, ["proxy:"]);
if ($isParsing && isset($args['proxy'])) {
    list($proxyHost, $proxyPort) = explode(':', $args['proxy']);
}

if ($isParsing || $isLocal) {
    $url = 'https://dlxcasino.com/api/games/allowed_desktop';

    $ch = curl_init($url);
    if (!empty($proxyHost) && !empty($proxyPort)) {
        curl_setopt($ch, CURLOPT_PROXY, $proxyHost);
        curl_setopt($ch, CURLOPT_PROXYPORT, $proxyPort);
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    }
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'cookie: __ddg1_=Zm5wrZoh4JnvO4ROIJFY'
    ));

    $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 = [];

if ($isLocal || $isProd) {
    require_once 'pdo.php'; // Include your database connection settings

    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);
} else {

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

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

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