<?php

require_once 'pdo.php';
require_once 'simple_html_dom.php'; // Include Simple HTML DOM Parser

$casino_id = 33;
$name = 'videoslots';

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

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

if ($isLocal) {
    $baseURL = 'https://www.videoslots.com/phive/modules/BoxHandler/html/ajaxActions.php?func=printGameList&boxid=744&action=GetBoxHtml&page=';
    $numPages = 31; // Change this to the number of pages you want to scrape

    $allGames = [];

    for ($page = 1; $page <= $numPages; $page++) {
        $url = $baseURL . $page;
        $html = file_get_html($url); // Load the HTML content from the URL

        // Loop through each game element
        foreach ($html->find('div.game-text a') as $gameElement) {
            // Extract game_name from the HTML
            $game_name = trim($gameElement->plaintext);

            // Add the game_name to the array
            $allGames[] = [
                'game_name' => $game_name,
                'provider_name' => "",
            ];
        }

        // Sleep for a while to avoid overloading the server
        sleep(2); // Adjust the delay as needed
    }

    // Save the scraped data to the file
    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);

// Process and insert the game data into the database as needed
$insertedGames = [];
foreach ($games as $game) {
    $game_name = $game["game_name"];
    $provider_name = ''; // You can set provider_name if needed

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

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