<?php
include "config.php";

$allowed = [
    'total_margin', 'active_trading', 'total_lots', 'stop_outs',
    'profit_order', 'profitability_score', 'new_users',
    'spread_cost', 'rollover_cost', 'net_deposit',
    'net_withdrawal', 'active_funds'
];

function getBrokerLogo($name) {
    $logos = [
        'FBS' => '/uploads/fbs.png',
        'Exness' => '/uploads/exness.png',
        'IC Markets Global' => '/uploads/icmarketsglobal.png'
    ];
    return $logos[$name] ?? '/uploads/logo-grey.png';
}
?>

<div class="carousel-container">
    <?php foreach ($allowed as $filter): 
        $stmt = $dbh->prepare("SELECT * FROM broker_rankings ORDER BY `$filter` DESC LIMIT 10");
        $stmt->execute();
        $brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>
    <div class="table-wrapper" id="section-<?= $filter ?>">
        <h3><?= ucwords(str_replace("_", " ", $filter)) ?> Rankings</h3>
        <table class="ranking-table">
            <thead>
                <tr><th>#</th><th>Broker</th><th>Value</th><th>Status</th></tr>
            </thead>
            <tbody>
                <?php foreach ($brokers as $i => $broker): 
                    $rank = $i + 1;
                    $class = $rank === 1 ? 'rank-1' : ($rank === 2 ? 'rank-2' : ($rank === 3 ? 'rank-3' : 'rank-default'));
                ?>
                <tr>
                    <td><div class="rank-badge <?= $class ?>"><?= $rank ?></div></td>
                    <td>
                        <img src="<?= getBrokerLogo($broker['broker_name']) ?>" class="broker-logo" alt="">
                        <?= htmlspecialchars($broker['broker_name']) ?>
                    </td>
                    <td><?= number_format($broker[$filter], 2) ?></td>
                    <td>–</td>
                </tr>
                <?php endforeach ?>
            </tbody>
        </table>
    </div>
    <?php endforeach ?>
</div>

<style>
.carousel-container {
    display: flex;
    overflow-x: auto;
    scroll-behavior: smooth;
    gap: 30px;
    padding-bottom: 20px;
}
.carousel-container::-webkit-scrollbar { display: none; }
.table-wrapper {
    min-width: 500px;
    flex: 0 0 auto;
    background: white;
    padding: 16px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.ranking-table { width: 100%; border-collapse: collapse; }
.ranking-table th, .ranking-table td {
    padding: 10px; border-bottom: 1px solid #eee;
}
.rank-badge {
    width: 36px; height: 36px;
    border-radius: 50%;
    line-height: 36px;
    text-align: center;
    color: #fff; font-weight: bold;
}
.rank-1 { background: gold; }
.rank-2 { background: silver; }
.rank-3 { background: #cd7f32; }
.rank-default { background: #bbb; }
.broker-logo {
    width: 36px; height: 36px;
    object-fit: contain;
    border-radius: 5px;
    margin-right: 8px;
    vertical-align: middle;
}
</style>
