<?php
require '/mnt/www-live/TechOdyssey_Designs_Dashboard/vendor/autoload.php';
require '/mnt/www-live/TechOdyssey_Designs_Dashboard/src/db.php';
require_once '/mnt/www-live/TechOdyssey_Designs_Dashboard/src/envLoader.php';
loadEnv(__DIR__ . '/../../.env');

use Goutte\Client;

// Function to scrape price
function scrapePrice($url) {
    $client = new Client();  // Reinitialize client for each request
    try {
        $crawler = $client->request('GET', $url);

        $whole = $crawler->filter('.a-price-whole')->count() ? $crawler->filter('.a-price-whole')->text() : '0';
        $fraction = $crawler->filter('.a-price-fraction')->count() ? $crawler->filter('.a-price-fraction')->text() : '00';

        $whole = preg_replace('/[^0-9]/', '', $whole);
        $fraction = preg_replace('/[^0-9]/', '', $fraction);
        $fraction = strlen($fraction) === 1 ? $fraction . '0' : substr($fraction, 0, 2);

        $totalPrice = floatval($whole . '.' . $fraction);

        return $totalPrice;
    } catch (Exception $e) {
        return null;
    }
}

// Fetch all filaments
try {
    $stmt = $pdo->query("SELECT * FROM filamentTracker");
    $filaments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($filaments as $filament) {
        $amazonUrl = $filament['amazonUrl'];
        $filamentId = $filament['id'];

        // Scrape price
        $totalPrice = scrapePrice($amazonUrl);

        if ($totalPrice !== null && $totalPrice > 0) {
            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price) 
                VALUES (:filamentId, :price)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $totalPrice
            ]);

            echo "Updated price for {$filament['filamentName']}: £{$totalPrice}\n";
        } else {
            echo "Failed to update {$filament['filamentName']} (no price found or £0).\n";
        }

        // Add a small random delay between 1 to 5 seconds
        sleep(rand(1, 5));
    }
} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}
?>
