<?php
function getGameListAndSaveToDatabase($providerCode = "PRAGMATICLIVE")
{
    // Define the API endpoint and credentials
    $url = "https://api.nexusggr.com";
    $data = [
        "method" => "game_list",
        "agent_code" => "anak_2",
        "agent_token" => "4bee33f2233e7e5db50618571cd6f29a",
        "provider_code" => $providerCode
    ];

    // Set up the POST request with cURL
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    // Execute the request and capture the response
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Decode the JSON response
    $result = json_decode($response, true);

    // Check if the response is successful
    if ($httpCode == 200 && isset($result['status']) && $result['status'] == 1) {
        // Database connection setup
        $host = 'localhost';  // Update with your database host
        $user = 'mpo2';   // Update with your database username
        $password = 'mpo2'; // Update with your database password
        $database = 'mpo2'; // Update with your database name

        try {
            // Create a new PDO instance
            $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Prepare the SQL statement for inserting data
            $stmt = $pdo->prepare("INSERT INTO tb_gamenew (game_code, game_name, game_provider, game_category, game_image) 
                                   VALUES (:game_code, :game_name, :game_provider, :game_category, :game_image)");

            // Loop through each game and insert into the database
            foreach ($result['games'] as $game) {
                $stmt->execute([
                    ':game_code' => $game['game_code'],
                    ':game_name' => $game['game_name'],
                    ':game_provider' => $providerCode,
                    ':game_category' => 'casino',
                    ':game_image' => $game['banner']
                ]);
            }

            echo "Games inserted successfully into the database.";

        } catch (PDOException $e) {
            echo "Database error: " . $e->getMessage();
        }
    } else {
        // Handle failure or connection issues
        echo isset($result['msg']) ? "Error: " . $result['msg'] : "Failed to connect or invalid response.";
    }
}

// Run the function
getGameListAndSaveToDatabase("PRAGMATICLIVE");

?>