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

// Include all adapters
foreach (glob(__DIR__ . '/integrations/*Adapter.php') as $filename) {
    require_once $filename;
}

function calculate_effective_price($listing) {
    return min($listing['original_price'], $listing['discounted_price'], $listing['coupon_price']);
}

function calculate_final_score($listing) {
    // A simple scoring algorithm, can be improved
    $price_score = 100 - (calculate_effective_price($listing) / 10); // Lower price is better
    $rating_score = $listing['rating'] * 20; // Higher rating is better
    return $price_score + $rating_score;
}

function sync_data() {
    $pdo = db();
    $products = $pdo->query("SELECT * FROM products")->fetchAll(PDO::FETCH_ASSOC);
    $platforms = $pdo->query("SELECT * FROM platforms")->fetchAll(PDO::FETCH_ASSOC);

    $adapters = [];
    foreach ($platforms as $platform) {
        $class_name = ucfirst($platform['slug']) . 'Adapter';
        if (class_exists($class_name)) {
            $adapters[$platform['id']] = new $class_name();
        }
    }

    foreach ($products as $product) {
        $cheapest_listing = null;
        $top_rated_listing = null;
        $best_deal_listing = null;

        foreach ($platforms as $platform) {
            if (!isset($adapters[$platform['id']])) {
                continue;
            }

            $adapter = $adapters[$platform['id']];
            $price_data = $adapter->fetchProductPrice($product['name']);

            // Prepare listing data
            $listing_data = [
                'product_id' => $product['id'],
                'platform_id' => $platform['id'],
                'original_price' => $price_data['original_price'],
                'discounted_price' => $price_data['discounted_price'],
                'coupon_price' => $price_data['coupon_price'],
                'rating' => $price_data['rating'],
                'product_url' => $price_data['url'],
                'last_synced_at' => date('Y-m-d H:i:s'),
            ];

            $listing_data['effective_price'] = calculate_effective_price($listing_data);
            $listing_data['final_score'] = calculate_final_score($listing_data);

            // Insert or update listing
            $stmt = $pdo->prepare("SELECT id FROM product_listings WHERE product_id = :product_id AND platform_id = :platform_id");
            $stmt->execute(['product_id' => $product['id'], 'platform_id' => $platform['id']]);
            $existing_listing_id = $stmt->fetchColumn();

            if ($existing_listing_id) {
                $sql = "UPDATE product_listings SET original_price = :original_price, discounted_price = :discounted_price, coupon_price = :coupon_price, rating = :rating, product_url = :product_url, last_synced_at = :last_synced_at, effective_price = :effective_price, final_score = :final_score WHERE id = :id";
                $listing_data['id'] = $existing_listing_id;
            } else {
                $sql = "INSERT INTO product_listings (product_id, platform_id, original_price, discounted_price, coupon_price, rating, product_url, last_synced_at, effective_price, final_score) VALUES (:product_id, :platform_id, :original_price, :discounted_price, :coupon_price, :rating, :product_url, :last_synced_at, :effective_price, :final_score)";
            }
            $pdo->prepare($sql)->execute($listing_data);
            $listing_id = $existing_listing_id ?: $pdo->lastInsertId();

            // Badge logic
            $listing_data['id'] = $listing_id;
            if (!$cheapest_listing || $listing_data['effective_price'] < $cheapest_listing['effective_price']) {
                $cheapest_listing = $listing_data;
            }
            if (!$top_rated_listing || $listing_data['rating'] > $top_rated_listing['rating']) {
                $top_rated_listing = $listing_data;
            }
            if (!$best_deal_listing || $listing_data['final_score'] > $best_deal_listing['final_score']) {
                $best_deal_listing = $listing_data;
            }
        }

        // Update badges
        $pdo->prepare("UPDATE product_listings SET badge = NULL WHERE product_id = ?")->execute([$product['id']]);
        if ($cheapest_listing) {
            $pdo->prepare("UPDATE product_listings SET badge = 'CHEAPEST' WHERE id = ?")->execute([$cheapest_listing['id']]);
        }
        if ($top_rated_listing) {
            $pdo->prepare("UPDATE product_listings SET badge = CASE WHEN badge IS NULL THEN 'TOP RATED' ELSE CONCAT(badge, ', TOP RATED') END WHERE id = ?")->execute([$top_rated_listing['id']]);
        }
        if ($best_deal_listing) {
            $pdo->prepare("UPDATE product_listings SET badge = CASE WHEN badge IS NULL THEN 'BEST DEAL' ELSE CONCAT(badge, ', BEST DEAL') END WHERE id = ?")->execute([$best_deal_listing['id']]);
        }
    }

    echo "Sync completed successfully.\n";
}

sync_data();
