<?php 
// For initial page load, load brokers sorted by default filter 'total_margin'
$defaultFilter = 'total_margin';
$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'
];

// Sanitize filter from GET or default
$filter = in_array($_GET['filter'] ?? $defaultFilter, $allowed) ? ($_GET['filter'] ?? $defaultFilter) : $defaultFilter;

$stmt = $dbh->prepare("SELECT * FROM broker_rankings ORDER BY $filter DESC LIMIT 50");
$stmt->execute();
$brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Helper to get broker logo URL by name (update URLs as needed)
function getBrokerLogo($broker_name) {
    $logos = [
        'FBS' => 'https://eimgjys.fx696.com/ico/3981687359/FXT3981687359_843049.png_wiki-template-global',
        'Exness' => 'https://eimgjys.fx696.com/ico/638421411915938761/FXT638421411915938761_801538.png_wiki-template-global',
        'IC Markets Global' => 'https://eimgjys.fx696.com/ico/637576515574286814/FXT637576515574286814_667822.png_wiki-template-global',
        // Add more brokers here
    ];
    return $logos[$broker_name] ?? 'https://resources1.interface003.com/web20/img/default/20-20.png';
}

// Helper to create ranking movement dummy HTML (replace with real data if available)
function getRankingMovement($rank) {
    if ($rank == 1) return '--';
    $arr = ['up', 'down', 'none'];
    $choice = $arr[array_rand($arr)];
    if ($choice === 'up') return '<span class="up-txt">1 <i></i></span>';
    if ($choice === 'down') return '<span class="down-txt">2 <i></i></span>';
    return '<span class="normal">--</span>';
}
?>
<!DOCTYPE html>
<html>
<head>
    <style>
    .ranking {
        margin-top: 120px;
        font-family: Arial, sans-serif;
    }
    .rank-ul a {
        text-decoration: none;
        color: inherit;
    }
    .rank-ul {
        cursor: pointer;
        padding: 5px 10px;
        display: inline-block;
        margin-right: 10px;
    }
    .active {
        font-weight: bold;
        color: #007bff;
    }
    .list.rankList-list {
        margin-top: 20px;
        border: 1px solid #ddd;
        border-radius: 6px;
        overflow: hidden;
    }
    .title-tab-new {
        display: flex;
        justify-content: space-between;
        padding: 10px 15px;
        background: #f9f9f9;
        font-weight: 600;
        font-size: 16px;
    }
    .list-head ul, .list-list ul {
        display: flex;
        padding: 10px 15px;
        margin: 0;
        list-style: none;
        align-items: center;
    }
    .list-head ul {
        background: #efefef;
        font-weight: 600;
    }
    .list-list ul {
        border-top: 1px solid #ddd;
    }
    .list-1 {
        width: 50px;
        text-align: center;
    }
    .list-2 {
        flex: 2;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .list-3, .list-4 {
        flex: 1;
        text-align: center;
    }
    .com-img {
        height: 18px;
        width: auto;
    }
    .up-txt {
        color: green;
        font-weight: bold;
    }
    .down-txt {
        color: red;
        font-weight: bold;
    }
    .normal {
        color: gray;
    }
    </style>
</head>
<body>
<div class="ranking">
    <div class="title-tab">
        <ul id="tab-title" class="rank-transition">
            <?php foreach ($allowed as $key): ?>
                <li class="rank-ul <?= $filter == $key ? 'active' : '' ?>" data-filter="<?= htmlspecialchars($key) ?>">
                    <a href="javascript:void(0)"><?= ucwords(str_replace("_", " ", $key)) ?></a>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <div id="rankList" class="list rankList-list">
        <section class="title-tab title-tab-new jaf-1 list-title-list">
            <div class="title-l">
                <div class="title-l-t">
                    <h2 class="title-l-t-text" style="font-weight:600;font-size:16px;"><?= ucwords(str_replace('_', ' ', $filter)) ?></h2>
                </div>
            </div>
        </section>

        <div class="list-head">
            <ul>
                <li class="list-1"></li>
                <li class="list-2">Brokerage</li>
                <li class="list-3">Trading Volume%</li>
                <li class="list-4">Ranking<i></i></li>
            </ul>
        </div>

        <div class="list-list">
            <?php foreach ($brokers as $i => $broker):
                $rank = $i + 1;
                $bgColor = '';
                if ($rank == 1) $bgColor = 'background: rgba(255, 229, 178, 1); color: #330011; font-weight: 500;';
                elseif ($rank == 2) $bgColor = 'background: #e6eaf2; color: #330011;';
                elseif ($rank == 3) $bgColor = 'background: #f2e9df; color: #330011;';
            ?>
                <ul>
                    <li class="list-1"><span style="<?= $bgColor ?>"><?= $rank ?></span></li>
                    <li class="list-2">
                        <img alt="" src="<?= htmlspecialchars(getBrokerLogo($broker['broker_name'])) ?>" loading="lazy" class="com-img" />
                        <span><?= htmlspecialchars($broker['broker_name']) ?></span>
                    </li>
                    <li class="list-3"><?= number_format($broker['total_lots'], 2) ?></li>
                    <li class="list-4"><?= getRankingMovement($rank) ?></li>
                </ul>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const tabs = document.querySelectorAll('.rank-ul');
    const rankList = document.getElementById('rankList');

    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            // Remove active class from all
            tabs.forEach(t => t.classList.remove('active'));
            // Add active to clicked tab
            tab.classList.add('active');

            const filter = tab.getAttribute('data-filter');
            fetch(`get_brokers.php?filter=${encodeURIComponent(filter)}`)
                .then(res => res.json())
                .then(data => {
                    if (!Array.isArray(data)) throw new Error('Invalid data');
                    
                    // Clear current list
                    rankList.innerHTML = `
                        <section class="title-tab title-tab-new jaf-1 list-title-list">
                            <div class="title-l">
                                <div class="title-l-t">
                                    <h2 class="title-l-t-text" style="font-weight:600;font-size:16px;">${filter.replace(/_/g, ' ').toUpperCase()}</h2>
                                </div>
                            </div>
                        </section>
                        <div class="list-head">
                            <ul>
                                <li class="list-1"></li>
                                <li class="list-2">Brokerage</li>
                                <li class="list-3">Trading Volume%</li>
                                <li class="list-4">Ranking<i></i></li>
                            </ul>
                        </div>
                        <div class="list-list"></div>
                    `;

                    const listContainer = rankList.querySelector('.list-list');

                    // Helper to generate movement HTML on client (mimics PHP dummy)
                    function getRankingMovement(rank) {
                        if(rank === 1) return '--';
                        const choices = ['up', 'down', 'none'];
                        const choice = choices[Math.floor(Math.random() * choices.length)];
                        if (choice === 'up') return '<span class="up-txt">1 <i></i></span>';
                        if (choice === 'down') return '<span class="down-txt">2 <i></i></span>';
                        return '<span class="normal">--</span>';
                    }

                    // Helper to escape HTML
                    function escapeHtml(text) {
                        return text.replace(/[\"&'\/<>]/g, function (a) {
                            return {
                                '"': '&quot;', '&': '&amp;', "'": '&#39;',
                                '/': '&#47;', '<': '&lt;', '>': '&gt;'
                            }[a];
                        });
                    }

                    data.forEach((broker, i) => {
                        const rank = i + 1;
                        let bgColor = '';
                        if (rank === 1) bgColor = 'background: rgba(255, 229, 178, 1); color: #330011; font-weight: 500;';
                        else if (rank === 2) bgColor = 'background: #e6eaf2; color: #330011;';
                        else if (rank === 3) bgColor = 'background: #f2e9df; color: #330011;';

                        const logo = (() => {
                            const logos = {
                                'FBS': 'https://eimgjys.fx696.com/ico/3981687359/FXT3981687359_843049.png_wiki-template-global',
                                'Exness': 'https://eimgjys.fx696.com/ico/638421411915938761/FXT638421411915938761_801538.png_wiki-template-global',
                                'IC Markets Global': 'https://eimgjys.fx696.com/ico/637576515574286814/FXT637576515574286814_667822.png_wiki-template-global',
                            };
                            return logos[broker.broker_name] || 'https://resources1.interface003.com/web20/img/default/20-20.png';
                        })();

                        const ul = document.createElement('ul');
                        ul.innerHTML = `
                            <li class="list-1"><span style="${bgColor}">${rank}</span></li>
                            <li class="list-2"><img alt="" src="${logo}" loading="lazy" class="com-img" /><span>${escapeHtml(broker.broker_name)}</span></li>
                            <li class="list-3">${parseFloat(broker.total_lots).toFixed(2)}</li>
                            <li class="list-4">${getRankingMovement(rank)}</li>
                        `;
                        listContainer.appendChild(ul);
                    });
                })
                .catch(err => {
                    rankList.innerHTML = `<p style="color:red;">Failed to load data</p>`;
                    console.error(err);
                });
        });
    });
});
</script>
</body>
</html>
