<?php

require_once 'pdo.php';

$casino_id = 26;
$name = 'voltslot';

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

// Define the URL for scraping
$url = "https://gamble-free.com/voltslot.html";

if ($isLocal) {
    // Load the HTML content from the local file
    $htmlFile = $directory . '/gamble-free.com.parsing/casinos/' . $name . '.html';
    $html = file_get_contents($htmlFile);
} else {
    // Initialize cURL session
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL and store the response in $html
    $html = curl_exec($ch);

    // Close cURL session
    curl_close($ch);
}

if ($html) {
    // Use regular expressions to extract game data
    preg_match_all('/<div class="gameCard__name">(.*?)<\/div>/', $html, $gameNames);
    preg_match_all('/<div class="gameCard__provider">(.*?)<\/div>/', $html, $providerNames);

    $allGames = [];

    foreach ($gameNames[1] as $index => $gameName) {
        $game_name = strip_tags(trim($gameName));
        $provider_name = isset($providerNames[1][$index]) ? strip_tags(trim($providerNames[1][$index])) : "";

        if (!empty($game_name)) {
            // Add the game data to the array
            $allGames[] = [
                'game_name' => $game_name,
                'provider_name' => $provider_name,
            ];
        }
    }

    // Save the extracted data to the JSON file
    $jsonFile = $directory . '/gamble-free.com.parsing/casinos/' . $name . '.json';
    file_put_contents($jsonFile, json_encode($allGames, JSON_PRETTY_PRINT));
} else {
    echo "Failed to retrieve HTML content.\n";
}

// Load games from the stored JSON file
$jsonFile = $directory . '/gamble-free.com.parsing/casinos/' . $name . '.json';

if (!file_exists($jsonFile)) {
    echo "JSON file does not exist: $jsonFile\n";
    exit;
}

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

$insertedGames = [];

foreach ($games as $game) {
    $game_name = $game["game_name"];
    $game_name = str_replace(" Mobile", "", $game_name);
    $provider_name = $game["provider_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[] = [
        'game_name' => $game_name,
        'provider_name' => $provider_name,
    ];
}

// Now you can echo or save the scraped data as JSON
echo json_encode(['insertedGames' => $insertedGames, 'count' => count($insertedGames)], JSON_PRETTY_PRINT);

?>
