<?php
require __DIR__ . '/../config/db.php';

$stmt = $pdo->query("
    SELECT * FROM rates r1
    JOIN rates r2 ON r1.exchange != r2.exchange
    ORDER BY (r2.price_sell - r1.price_buy) DESC
    LIMIT 1
");

$best = $stmt->fetch(PDO::FETCH_ASSOC);
if ($best) {
    $profit = $best['price_sell'] - $best['price_buy'];
    $roi = ($profit / $best['price_buy']) * 100;

    $stmt2 = $pdo->prepare("
        INSERT INTO profits (bestBuyEx, bestBuyRate, bestSellEx, bestSellRate, totalProfit, roi)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt2->execute([$best['exchange'], $best['price_buy'], $best['exchange'], $best['price_sell'], $profit, $roi]);
}
