<?php
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../config.php';

function seed_product_listings() {
    $faker = Faker\Factory::create();
    $pdo = db();

    // Fetch product and platform IDs
    $product_ids = $pdo->query("SELECT id FROM products")->fetchAll(PDO::FETCH_COLUMN);
    $platform_ids = $pdo->query("SELECT id FROM platforms")->fetchAll(PDO::FETCH_COLUMN);

    if (empty($product_ids) || empty($platform_ids)) {
        echo "Please seed products and platforms first.\n";
        return;
    }

    $listings = [];
    foreach ($product_ids as $product_id) {
        $num_listings = rand(1, count($platform_ids));
        $used_platforms = [];
        for ($i = 0; $i < $num_listings; $i++) {
            $platform_id = $platform_ids[array_rand($platform_ids)];
            if (in_array($platform_id, $used_platforms)) {
                continue;
            }
            $used_platforms[] = $platform_id;

            $original_price = $faker->randomFloat(2, 10, 1000);
            $discounted_price = $original_price - $faker->randomFloat(2, 0, $original_price * 0.5);
            $coupon_price = $discounted_price - $faker->randomFloat(2, 0, $discounted_price * 0.2);

            $listings[] = [
                'product_id' => $product_id,
                'platform_id' => $platform_id,
                'original_price' => $original_price,
                'discounted_price' => $discounted_price,
                'coupon_price' => $coupon_price,
                'rating' => $faker->randomFloat(1, 1, 5),
                'product_url' => $faker->url,
            ];
        }
    }

    $stmt = $pdo->prepare("INSERT INTO product_listings (product_id, platform_id, original_price, discounted_price, coupon_price, rating, product_url) VALUES (:product_id, :platform_id, :original_price, :discounted_price, :coupon_price, :rating, :product_url)");

    foreach ($listings as $listing) {
        $stmt->execute($listing);
    }

    echo count($listings) . " product listings seeded successfully.\n";
}

seed_product_listings();
