<?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';
require 'scraper.php';
loadEnv(__DIR__ . '/../../.env');

// 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'];

        // Use the scraper function to fetch price and discount
        $scrapedData = scrapeAmazonData($amazonUrl);

        if ($scrapedData && $scrapedData['price'] > 0) {
            // Prepare currentDiscount JSON structure with the correct format
            $currentDiscount = json_encode([
                'discount' => [
                    'value' => $scrapedData['currentDiscount']['discount']['value'] ?? 0,
                    'type' => $scrapedData['currentDiscount']['discount']['type'] ?? 'percentage',
                ],
                'voucher' => [
                    'value' => $scrapedData['currentDiscount']['voucher']['value'] ?? 0,
                    'type' => $scrapedData['currentDiscount']['voucher']['type'] ?? null,
                ],
            ]);

            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price, currentDiscount) 
                VALUES (:filamentId, :price, :currentDiscount)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $scrapedData['price'],
                ':currentDiscount' => $currentDiscount
            ]);

            echo "Updated price for {$filament['filamentName']}: £{$scrapedData['price']}, Current Discount: {$currentDiscount}\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();
}
