<?php
// 1. PHP Logic Sabse Upar (Data Fetching & Processing)
include __DIR__ . '/../config.php';

// Get selected regulators
$regulators = $_GET['regulators'] ?? [];

// Get pagination settings
$limit = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Get available regulators
$sql = "SELECT DISTINCT regulator FROM brokers WHERE regulator IS NOT NULL AND regulator != ''";
$regStmt = $dbh->query($sql);
$availableRegulators = $regStmt->fetchAll(PDO::FETCH_COLUMN);

// Mapping full regulator names to short forms
$regShortForms = [
    'Financial Conduct Authority' => 'FCA',
    'Australia Securities & Investment Commission' => 'ASIC',
    'Cyprus Securities and Exchange Commission' => 'CySEC',
    'Securities and Exchange Commission' => 'SEC',
    'Financial Services Authority' => 'FSA',
    'Monetary Authority of Singapore' => 'MAS',
    'Commodity Futures Trading Commission' => 'CFTC',
    'Securities and Exchange Regulator of Cambodia' => 'SERC',
    'Central Bank of Russia' => 'CBR',
    'ASIC Market Maker (MM)' => 'ASIC MM',
    'FCA Market Maker (MM)' => 'FCA MM',
    'ASIC Market Maker (MM), FCA Market Maker (MM)' => 'ASIC (MM) FCA (MM)',
    'CYSEC Straight Through Processing (STP)' => 'CYSEC STP',
    'ASIC Leveraged Foreign Exchange Trading' => 'ASIC LFET'
];

// Filter condition
$regulatorCondition = "";
$params = [];

if (!empty($regulators)) {
    $placeholders = implode(',', array_fill(0, count($regulators), '?'));
    $regulatorCondition = "WHERE regulator IN ($placeholders)";
    $params = $regulators;
}

// Count total
$countSql = "SELECT COUNT(*) FROM brokers $regulatorCondition";
$countStmt = $dbh->prepare($countSql);
$countStmt->execute($params);
$totalBrokers = $countStmt->fetchColumn();
$totalPages = ceil($totalBrokers / $limit);

// Get paginated brokers
$sql = "SELECT * FROM brokers $regulatorCondition LIMIT $limit OFFSET $offset";
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include __DIR__ . '/../includes/header.php'; ?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo $base_url; ?>/assets/css/flagranking.css">
<?php
$currentPage = basename($_SERVER['PHP_SELF']);

function ranking_tab_class(array $pages, string $currentPage): string {
    return in_array($currentPage, $pages, true) ? ' active' : '';
}
?>
<style>
    .hover-shadow {
        transition: box-shadow 0.2s ease, transform 0.2s ease;
    }

    .hover-shadow:hover {
        box-shadow: 0 8px 20px rgba(17, 24, 39, 0.12);
        transform: translateY(-1px);
    }
</style>


<div class="ranking-list">
    <div class="mx-auto w-1200 lg:w-940 md:w-760 sm:w-full sm:bg-[#fff]">
        <div class="tab-box sm:mx-16"></div>

        <div class="content">
            <div class="content-left">
                <div class="list-box">
                    <div class="mb-20 flex h-36 items-center overflow-hidden rounded-2 bg-[#FEFAE7] px-20 text-14 leading-20 text-[#927D31] sm:mb-0">
                        <div direction="col" class="wiki_text_scroll">
                            <span class="text_warp" style="padding-right:0px;">※ Here are the browsing rankings in India on WikiFX, which may vary by region</span>
                        </div>
                    </div>

                    <div class="tab-box sm:mx-16">
                        <section class="article-tab">
                            <div class="tab">
                                <div class="tab-l tab-l-show">
                                    <div class="father-position jaf-0">
                                        <div class="position flex">
                                            <a class="span-link<?= ranking_tab_class(['flagranking.php'], $currentPage) ?>" href="<?php echo $base_url; ?>/ranking/flagranking.php"><span>Rankings</span></a>
                                            <a class="span-link<?= ranking_tab_class(['brandranking.php'], $currentPage) ?>" href="<?php echo $base_url; ?>/ranking/brandranking.php"><span>Brand Ranking</span></a>
                                            <a class="span-link<?= ranking_tab_class(['popularity.php'], $currentPage) ?>" href="<?php echo $base_url; ?>/ranking/popularity.php"><span>Popularity Ranking</span></a>
                                            <a class="span-link<?= ranking_tab_class(['blackranking.php'], $currentPage) ?>" href="<?php echo $base_url; ?>/ranking/blackranking.php"><span>Frauds</span></a>
                                            <a class="span-link<?= ranking_tab_class(['low-spreads.php'], $currentPage) ?>" href="<?php echo $base_url; ?>/ranking/low-spreads.php"><span>Spread Ranking</span></a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </div>

                    <div class="sm:mx-16"></div>

                    <div class="container px-0">
                        <form id="filterForm" method="GET">
                            <div class="filter-box-container">
                                <?php foreach ($availableRegulators as $reg):
                                    $short = $regShortForms[$reg] ?? $reg;
                                    $checked = isset($regulators[0]) && $regulators[0] === $reg;
                                ?>
                                    <label class="filter-box <?= $checked ? 'selected' : '' ?>">
                                        <input type="radio" name="regulators[]" value="<?= htmlentities($reg) ?>" <?= $checked ? 'checked' : '' ?>>
                                        <?= htmlentities($short) ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </form>

                        <div class="list-box">
                            <?php if (count($results) > 0): ?>
                                <?php foreach ($results as $row): ?>
                                    <a href="<?php echo $base_url; ?>/avatrade.php?name=<?= strtolower(urlencode($row['name'])) ?>" class="list-box-item d-flex flex-wrap flex-md-nowrap align-items-center border rounded p-3 mb-3 bg-white text-dark text-decoration-none shadow-sm">
                                        <div class="item-left me-3 mb-3 mb-md-0">
                                            <div class="img-box position-relative border rounded bg-light d-flex align-items-center justify-content-center p-1" style="width: 80px; height: 80px;">
                                                <img src="<?php echo $base_url; ?>/uploads/<?= htmlentities($row['logo']) ?>" alt="<?= htmlentities($row['name']) ?>" class="img-fluid" style="object-fit: contain; max-height: 100%;">
                                                <div class="regulated-tag">Regulated</div>
                                            </div>
                                        </div>

                                        <div class="text-box flex-grow-1 me-auto">
                                            <div class="fw-bold mb-1 fs-5"><?= htmlentities($row['name']) ?></div>
                                            <div class="flag-box mb-2">
                                                <img src="https://flagcdn.com/w40/ie.png" alt="flag" width="25">
                                            </div>

                                            <div class="d-md-none d-block mb-2">
                                                <small class="text-muted">Average Spread</small><br>
                                                <strong><?= htmlentities($row['spread'] ?? 'N/A') ?></strong>
                                            </div>

                                            <div class="d-flex flex-wrap gap-2 mt-2">
                                                <span class="badge border text-secondary fw-normal">10-15 years</span>
                                                <span class="badge border text-secondary fw-normal"><?= htmlentities($row['regulator']) ?></span>
                                                <span class="badge border text-secondary fw-normal">MT5 Full License</span>
                                            </div>
                                        </div>

                                        <div class="item-right text-end d-none d-md-block ms-3" style="min-width: 100px;">
                                            <div class="text-muted small">Average Spread</div>
                                            <div class="fs-5 fw-bold text-primary"><?= htmlentities($row['spread'] ?? 'N/A') ?></div>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="alert alert-warning text-center">No brokers found for the selected filters.</div>
                            <?php endif; ?>
                        </div>

                        <?php if ($totalPages > 1): ?>
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center mt-4">
                                    <?php for ($i = 1; $i <= $totalPages; $i++):
                                        $queryParams = $_GET;
                                        $queryParams['page'] = $i;
                                        $link = http_build_query($queryParams);
                                    ?>
                                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                            <a class="page-link" href="<?php echo $base_url; ?>/ranking/low-spreads.php?<?= $link ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="content-right">
                <div class="title">Trader Safety Express</div>
                <div class="list-box">
                    <?php
                    $sidebar_brokers = [
                        'xm' => ['name' => 'XM', 'img' => '0001461138/FXT0001461138_170305.png'],
                        'avatrade' => ['name' => 'AvaTrade', 'img' => '638524966772430100/FXT638524966772430100_419753.png'],
                        'fxcm' => ['name' => 'FXCM', 'img' => '0001698019/FXT_0001698019_100x100.png'],
                        'exness' => ['name' => 'Exness', 'img' => '638421411915938761/FXT638421411915938761_801538.png'],
                        'finowiz' => ['name' => 'FINOWIZ', 'img' => '2257270373/FXT2257270373_297129.png'],
                        'botbro' => ['name' => 'BotBro', 'img' => '1225957382/FXT1225957382_671125.png'],
                        'startrader' => ['name' => 'STARTRADER', 'img' => '637853008755653991/FXT637853008755653991_593518.png'],
                        'icmarketsglobal' => ['name' => 'IC Markets Global', 'img' => '637576515574286814/FXT637576515574286814_667822.png'],
                        'fxtm' => ['name' => 'FXTM', 'img' => '638678860542341398/FXT638678860542341398_670686.png'],
                        'vantage' => ['name' => 'Vantage', 'img' => '637769787885521747/FXT637769787885521747_425825.png']
                    ];

                    foreach ($sidebar_brokers as $slug => $data):
                    ?>
                        <a href="<?php echo $base_url; ?>/avatrade.php?name=<?= $slug ?>" target="_blank">
                            <img alt="<?= $data['name'] ?>" src="https://eimgjys.fxeyee.com/ico/<?= $data['img'] ?>_wiki-template-global" loading="lazy" class="com-img" style="height:100%;">
                            <?= $data['name'] ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="el-dialog__wrapper" style="display:none;">
        <div role="dialog" aria-modal="true" aria-label="All" class="el-dialog rankingList-dialog" style="margin-top:15vh;">
            <div class="el-dialog__header">
                <span class="el-dialog__title">All</span>
                <button type="button" aria-label="Close" class="el-dialog__headerbtn">
                    <i class="el-dialog__close el-icon el-icon-close"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<section style="padding-bottom:0;">
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.filter-box input[type="radio"]').forEach(input => {
            input.addEventListener('change', function() {
                this.closest('form').submit();
            });
        });
    });
</script>

</body>
</html>
