<?php
require '../../vendor/autoload.php';
require '../db.php';
require_once '../envLoader.php';
loadEnv('../../.env');

require_once '../emailService/sendPriceDropEmailService.php';

// Fetch list of all filaments being tracked
function getFilaments() {
    global $pdo;
    try {
        $stmt = $pdo->query("SELECT id, filamentName, brand, amazonUrl FROM filamentTracker");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        echo "Error fetching filaments: " . $e->getMessage();
        return [];
    }
}

// Fetch the latest prices for each filament
function getCurrentPrices() {
    global $pdo;
    try {
        $stmt = $pdo->query("
            SELECT fp.filamentId, fp.price, fp.recordedAt
            FROM filamentPriceHistory fp
            INNER JOIN (
                SELECT filamentId, MAX(recordedAt) AS latestRecordedAt
                FROM filamentPriceHistory
                GROUP BY filamentId
            ) latest ON fp.filamentId = latest.filamentId AND fp.recordedAt = latest.latestRecordedAt
        ");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        echo "Error fetching current prices: " . $e->getMessage();
        return [];
    }
}

// Fetch prices from the last 24 hours for each filament
function getPriceHistoryForLast24Hours() {
    global $pdo;
    try {
        $stmt = $pdo->query("
            SELECT filamentId, price, recordedAt
            FROM filamentPriceHistory
            WHERE recordedAt >= NOW() - INTERVAL 1 DAY
            ORDER BY filamentId, recordedAt DESC
        ");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        echo "Error fetching price history for the last 24 hours: " . $e->getMessage();
        return [];
    }
}

// Compare prices and find drops
function checkPriceDropsAndNotify() {
    $filaments = getFilaments();
    $currentPrices = getCurrentPrices();
    $priceHistory = getPriceHistoryForLast24Hours();

    // Index prices by filamentId for quick lookup
    $currentPricesMap = [];
    foreach ($currentPrices as $current) {
        $currentPricesMap[$current['filamentId']] = $current['price'];
    }

    // Group price history by filamentId
    $priceHistoryMap = [];
    foreach ($priceHistory as $history) {
        $priceHistoryMap[$history['filamentId']][] = $history['price'];
    }

    $priceDrops = [];

    foreach ($filaments as $filament) {
        $filamentId = $filament['id'];
        $currentPrice = $currentPricesMap[$filamentId] ?? null;

        if ($currentPrice !== null && isset($priceHistoryMap[$filamentId])) {
            foreach ($priceHistoryMap[$filamentId] as $oldPrice) {
                if ($currentPrice < (float)$oldPrice) {
                    $priceDrops[] = [
                        'filamentName' => $filament['filamentName'],
                        'brand' => $filament['brand'] ?: 'Unknown',
                        'newPrice' => "£" . number_format($currentPrice, 2),
                        'oldPrice' => "£" . number_format((float)$oldPrice, 2),
                        'priceChange' => "-£" . number_format((float)$oldPrice - $currentPrice, 2),
                        'amazonUrl' => $filament['amazonUrl']
                    ];
                    break; // Stop checking once a price drop is detected
                }
            }
        }
    }

    function getRecipients() {
        global $pdo;
        try {
            $stmt = $pdo->query("SELECT `email` FROM `users` WHERE `alertEmails` = 1");
            return $stmt->fetchAll(PDO::FETCH_COLUMN);
        } catch (PDOException $e) {
            echo "Error fetching recipients: " . $e->getMessage();
            return [];
        }
    }

    // Send email if there are price drops
    if (!empty($priceDrops)) {
        $recipient = getRecipients();
        $subject = 'Filament Price Change Summary';
        $data = [
            'filaments' => $priceDrops,
            'dashboardUrl' => $_ENV['WEBSITE_URL'] . '/dashboard'
        ];

        sendEmail($recipient, $subject, 'filament_price_summary', $data);

        echo "Email sent for the following price drops:\n";
        foreach ($priceDrops as $drop) {
            echo "- {$drop['filamentName']}: Price dropped from {$drop['oldPrice']} to {$drop['newPrice']}\n";
        }
    } else {
        echo "No price drops detected.\n";
    }
}

checkPriceDropsAndNotify();

?>
