<?php
include __DIR__ . '/../config.php';

$regulators = $_GET['regulators'] ?? [];
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = 5;
$offset = ($page - 1) * $limit;

if (!empty($regulators)) {
    $placeholders = implode(',', array_fill(0, count($regulators), '?'));
    $count_sql = "SELECT COUNT(*) FROM brokers WHERE ";
    $conditions = array_fill(0, count($regulators), "FIND_IN_SET(?, regulator)");
    $count_sql .= implode(' OR ', $conditions);
    $count_stmt = $dbh->prepare($count_sql);
    $count_stmt->execute($regulators);
} else {
    $count_stmt = $dbh->query("SELECT COUNT(*) FROM brokers");
}

$total_brokers = $count_stmt->fetchColumn();
$total_pages = (int) ceil($total_brokers / $limit);

if (!empty($regulators)) {
    $where = implode(' OR ', array_fill(0, count($regulators), "FIND_IN_SET(?, regulator)"));
    $sql = "SELECT * FROM brokers WHERE {$where} LIMIT {$limit} OFFSET {$offset}";
    $stmt = $dbh->prepare($sql);
    $stmt->execute($regulators);
} else {
    $stmt = $dbh->prepare("SELECT * FROM brokers ORDER BY score DESC LIMIT {$limit} OFFSET {$offset}");
    $stmt->execute();
}

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css" rel="stylesheet">

<style>
    * {
        box-sizing: border-box;
    }

    .broker-rankings-page {
        width: 100%;
        max-width: 1400px;
        margin: 0 auto;
        padding: clamp(16px, 3vw, 32px) 0;
    }

    .broker-card {
        background: #fff;
        border: 1px solid #ddd;
        border-radius: 12px;
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.07);
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease;
    }

    .broker-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        border-color: #0d6efd;
    }

    .broker-card .row {
        --bs-gutter-x: 1.25rem;
        --bs-gutter-y: 1rem;
    }

    .broker-card h5 {
        margin-bottom: 0.75rem;
        word-break: break-word;
    }

    .broker-card .text-muted,
    .broker-card .badge,
    .broker-card a {
        word-break: break-word;
    }

    .broker-logo-container {
        min-height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px 0;
    }

    .broker-logo {
        width: 100%;
        max-width: 140px;
        max-height: 60px;
        object-fit: contain;
    }

    .badge-green {
        background-color: #28a745;
        color: #fff;
        font-size: 13px;
        font-weight: 500;
        padding: 4px 10px;
        border-radius: 20px;
    }

    .tag-badge {
        background-color: #eaf2ff;
        color: #333;
        border-radius: 5px;
        padding: 3px 8px;
        margin: 2px;
        font-size: 12px;
        display: inline-block;
    }

    .score-box {
        font-size: 26px;
        font-weight: bold;
        color: #b8860b;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        padding-left: 1rem;
        border-left: 1px solid #eee;
    }

    .score-box i {
        color: #ffc107;
    }

    .shield-badge {
        width: 40px;
        height: 50px;
        background: #ffc107;
        color: #333;
        font-weight: bold;
        font-size: 20px;
        text-align: center;
        line-height: 50px;
        clip-path: polygon(50% 0%, 100% 25%, 100% 80%, 50% 100%, 0% 80%, 0% 25%);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
    }

    .pagination {
        flex-wrap: wrap;
        gap: 8px;
    }

    .pagination .page-link {
        min-width: 42px;
        text-align: center;
    }

    @media (max-width: 992px) {
        .broker-card {
            padding: 20px;
        }

        .broker-logo-container {
            min-height: 70px;
        }

        .broker-logo {
            max-width: 125px;
        }
    }

    @media (max-width: 768px) {
        .broker-rankings-page {
            padding: 12px 0 20px;
        }

        .broker-card {
            padding: 16px;
            border-radius: 16px;
        }

        .broker-card .row {
            --bs-gutter-x: 0;
            --bs-gutter-y: 0.85rem;
        }

        .broker-card [class*="col-"] {
            flex: 0 0 100%;
            max-width: 100%;
            padding-left: 0;
            padding-right: 0;
        }

        .broker-card .col-4,
        .broker-card .col-8,
        .broker-card .col-12,
        .broker-card .col-md-1,
        .broker-card .col-md-2,
        .broker-card .col-md-7 {
            width: 100%;
        }

        .broker-card .col-4 {
            order: 1;
            text-align: left !important;
        }

        .broker-card .col-8 {
            order: 2;
        }

        .broker-card .col-12.col-md-2 {
            order: 3;
        }

        .broker-card .col-12.col-md-1 {
            order: 4;
        }

        .score-box {
            border-left: none;
            border-top: 1px solid #eee;
            padding: 14px 0 0;
            margin-top: 8px;
            justify-content: flex-start;
            text-align: left;
        }

        .broker-logo-container {
            min-height: 58px;
            justify-content: flex-start;
        }

        .broker-logo {
            max-width: 120px;
            max-height: 52px;
        }

        .shield-badge {
            width: 36px;
            height: 46px;
            line-height: 46px;
            font-size: 18px;
            margin-top: 0 !important;
        }

        .broker-card h5 {
            font-size: 1.05rem;
        }

        .broker-card .d-flex.align-items-center {
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .pagination.pagination-lg .page-link {
            padding: 0.45rem 0.7rem;
            font-size: 0.95rem;
        }
    }

    @media (max-width: 480px) {
        .broker-rankings-page {
            padding: 10px 0 16px;
        }

        .broker-card {
            padding: 14px;
            border-radius: 14px;
        }

        .broker-card h5 {
            font-size: 1rem;
        }

        .broker-logo-container {
            min-height: 50px;
        }

        .broker-logo {
            max-width: 110px;
            max-height: 48px;
        }

        .score-box {
            padding-top: 12px;
        }

        .score-box .display-6 {
            font-size: 1.9rem;
        }

        .tag-badge {
            display: inline-flex;
            margin-right: 0.35rem;
            margin-bottom: 0.35rem;
        }

        .pagination .page-link {
            min-width: 38px;
            padding: 0.35rem 0.6rem;
        }
    }

    @media (max-width: 768px) {
        #hi {
            display: none;
        }
    }
</style>

<div class="broker-rankings-page container">
    <?php if (empty($results)): ?>
        <div class="text-center py-5">
            <i class="bi bi-search display-1 text-muted"></i>
            <p class="mt-3">No brokers found matching your criteria.</p>
        </div>
    <?php endif; ?>

    <?php foreach ($results as $index => $row): ?>
        <?php
        $regulatorValue = $row['regulator'] ?? '';
        $countryValue = $row['country'] ?? '';
        $licenseNumber = trim((string) ($row['license_number'] ?? ''));
        $regList = array_filter(array_map('trim', explode(',', $regulatorValue)));
        $countryList = array_filter(array_map('trim', explode(',', $countryValue)));
        ?>
        <div class="broker-card" data-aos="fade-up" data-aos-delay="<?= $index * 100 ?>">
            <div class="row align-items-center">
                <div class="col-4 col-md-2 text-center mb-3 mb-md-0">
                    <div class="badge badge-green mb-2"><i class="bi bi-shield-check"></i> Regulated</div>
                    <div class="broker-logo-container">
                        <img src="../uploads/<?= htmlentities($row['logo'] ?: 'default-logo.png') ?>" alt="<?= htmlentities($row['name']) ?>" class="broker-logo">
                    </div>
                </div>

                <div class="col-8 col-md-7">
                    <h5><i class="bi bi-building me-1"></i><?= htmlentities($row['name']) ?></h5>
                    <div class="d-flex align-items-center mb-2">
                        <img src="https://flagcdn.com/w40/ie.png" width="22" class="me-2" alt="Flag">
                        <span class="me-3"><i class="bi bi-geo-alt"></i> Ireland</span>
                        <span class="me-3"><i class="bi bi-clock-history"></i> 15–20 years</span>
                        <span class="badge bg-light border text-dark" id="hi">Environment AA</span>
                    </div>

                    <div>
                        <?php foreach ($regList as $reg): ?>
                            <a href="#"><i class="bi bi-bank"></i> <?= htmlentities($reg) ?></a>
                            <span class="badge bg-success ms-1">Regulated</span><br>
                        <?php endforeach; ?>
                    </div>

                    <div class="mt-2">
                        <?php foreach ($countryList as $country): ?>
                            <span class="tag-badge"><i class="bi bi-check-circle"></i> Regulated in <?= htmlentities($country) ?></span>
                        <?php endforeach; ?>
                    </div>

                    <div class="text-muted mt-2">
                        <i class="bi bi-file-earmark-text"></i> Regulatory License Number: <?= htmlentities($licenseNumber !== '' ? $licenseNumber : 'N/A') ?>
                    </div>
                </div>

                <div class="col-12 col-md-2 text-end mt-2 mt-md-0">
                    <div class="score-box"><i class="bi bi-star-fill"></i> <?= htmlentities($row['score']) ?></div>
                    <div>Score</div>
                </div>

                <div class="col-12 col-md-1 text-end mt-1 mt-md-0">
                    <div class="shield-badge mx-auto mt-2">
                        <?= ($offset + $index + 1) ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <?php if ($total_pages > 1): ?>
        <div class="d-flex justify-content-center mt-4">
            <nav>
                <ul class="pagination pagination-lg">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo;</a>
                        </li>
                    <?php endif; ?>

                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">&raquo;</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
<script>
    AOS.init({
        duration: 800,
        once: true
    });
</script>