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

// 1. Pagination & Filter Logic
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = 10; 
$offset = ($page - 1) * $limit;
$regulators = $_GET['regulators'] ?? [];

// 2. Build Query based on filters
if (!empty($regulators)) {
    $placeholders = implode(',', array_fill(0, count($regulators), '?'));
    $sql = "SELECT * FROM brokers WHERE regulator IN ($placeholders) ORDER BY score DESC LIMIT $limit OFFSET $offset";
    $stmt = $dbh->prepare($sql);
    $stmt->execute($regulators);

    $countStmt = $dbh->prepare("SELECT COUNT(*) FROM brokers WHERE regulator IN ($placeholders)");
    $countStmt->execute($regulators);
} else {
    $stmt = $dbh->prepare("SELECT * FROM brokers ORDER BY score DESC LIMIT $limit OFFSET $offset");
    $stmt->execute();

    $countStmt = $dbh->prepare("SELECT COUNT(*) FROM brokers");
    $countStmt->execute();
}

$total = $countStmt->fetchColumn();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalPages = ceil($total / $limit);

// For clean pagination links
$requestUri = $_SERVER['REQUEST_URI'] ?? ($_SERVER['PHP_SELF'] ?? '');
$currentUrl = strtok($requestUri, '?');
$queryParams = $_GET;
?>

<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://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

<style>
    :root { --primary-color: #0d6efd; --score-color: #9e4229; }

    .broker-page {
        width: 100%;
        max-width: 1400px;
        margin: 0 auto;
        padding: clamp(16px, 3vw, 32px) 0;
    }
    
    .broker-link { text-decoration: none !important; color: inherit; }
    
    .broker-card {
        background: #fff;
        border: 1px solid #eaeaea;
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s cubic-bezier(.25,.8,.25,1);
    }
    
    .broker-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.08);
        border-color: var(--primary-color);
    }

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

    .broker-logo {
        max-width: 140px;
        width: 100%;
        max-height: 60px;
        object-fit: contain;
        position: relative;
        z-index: 1;
    }
    .broker-logo-container::before {
        content: '';
        position: absolute;
        inset: 0;
        background: url('<?php echo $base_url; ?>/assets/images/logo_bg.png') center center no-repeat;
        background-size: contain;
        opacity: 0.2;
        pointer-events: none;
    }

    .score-box {
        border-left: 1px solid #eee;
        color: var(--score-color);
    }

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

    .broker-card h4 {
        word-break: break-word;
    }

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

    .reg-badge {
        font-size: 0.75rem;
        padding: 4px 10px;
        border-radius: 50px;
    }

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

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

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

        .container.py-5 {
            padding-top: 0 !important;
            padding-bottom: 0 !important;
        }

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

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

        .broker-card .col-12 {
            padding-left: 0;
            padding-right: 0;
        }

        .broker-card .p-4 {
            padding: 1rem !important;
        }

        .score-box { 
            border-left: none; 
            border-top: 1px solid #eee; 
            padding-top: 14px; 
            margin-top: 8px;
        }

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

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

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

        .pagination {
            gap: 6px;
        }

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

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

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

        .broker-card .p-4 {
            padding: 0.9rem !important;
        }

        .broker-card h4 {
            font-size: 1rem;
            margin-bottom: 0.5rem !important;
        }

        .broker-card .d-flex.gap-3 {
            gap: 0.5rem !important;
        }

        .reg-badge {
            font-size: 0.7rem;
        }

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

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

<div class="broker-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 $row): ?>
        <div class="mb-4" data-aos="fade-up">
            <a href="details.php?id=<?= $row['id'] ?>" class="broker-link">
                <div class="broker-card p-4 shadow-sm">
                    <div class="row align-items-center">
                        
                        <div class="col-12 col-md-3">
                            <div class="mb-2">
                                <span class="badge bg-success-subtle text-success border border-success-subtle reg-badge">
                                    <i class="bi bi-shield-check me-1"></i>Regulated
                                </span>
                            </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-12 col-md-7 border-md-start px-md-4">
                            <h4 class="fw-bold mb-2"><?= htmlentities($row['name']) ?></h4>
                            
                            <div class="d-flex flex-wrap gap-3 mb-3 text-muted small">
                                <span><i class="bi bi-geo-alt me-1"></i>Global</span>
                                <span><i class="bi bi-calendar3 me-1"></i>Established: 10+ Years</span>
                                <span class="text-primary fw-bold">Environment AA</span>
                            </div>

                            <div class="mb-2">
                                <?php 
                                    $regList = array_unique(array_filter(array_map('trim', explode(',', $row['regulator']))));
                                    foreach ($regList as $reg): 
                                ?>
                                    <span class="me-2 badge bg-light text-dark border fw-normal">
                                        <i class="bi bi-patch-check-fill text-success me-1"></i><?= htmlentities($reg) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>

                            <div class="text-muted small">
                                <i class="bi bi-info-circle me-1"></i>
                                License: <?= !empty($row['license']) ? htmlentities($row['license']) : 'Verified' ?>
                            </div>
                        </div>

                        <div class="col-12 col-md-2 text-center score-box">
                            <div class="display-6 fw-bold mb-0">
                                <?= number_format($row['score'], 1) ?>
                            </div>
                            <div class="text-warning mb-1">
                                <i class="bi bi-star-fill"></i>
                                <i class="bi bi-star-fill"></i>
                                <i class="bi bi-star-fill"></i>
                                <i class="bi bi-star-fill"></i>
                                <i class="bi bi-star-half"></i>
                            </div>
                            <div class="small text-uppercase tracking-wider text-muted">Trust Score</div>
                        </div>

                    </div>
                </div>
            </a>
        </div>
    <?php endforeach; ?>

    <?php if ($totalPages > 1): ?>
    <nav class="mt-5">
        <ul class="pagination pagination-lg justify-content-center">
            <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                <?php $queryParams['page'] = $page - 1; ?>
                <a class="page-link" href="<?= $currentUrl . '?' . http_build_query($queryParams) ?>">
                    <i class="bi bi-chevron-left"></i>
                </a>
            </li>

            <?php for ($i = 1; $i <= $totalPages; $i++): 
                $queryParams['page'] = $i;
            ?>
                <li class="page-item <?= ($i === $page) ? 'active' : '' ?>">
                    <a class="page-link" href="<?= $currentUrl . '?' . http_build_query($queryParams) ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>

            <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                <?php $queryParams['page'] = $page + 1; ?>
                <a class="page-link" href="<?= $currentUrl . '?' . http_build_query($queryParams) ?>">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>
    AOS.init({
        duration: 800,
        once: true
    });
</script>