<?php
session_start();
include 'config.php';

$is_logged_in = isset($_SESSION['user_id']);

$limit = 24;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Search and Filter parameters
$search_query = isset($_GET['q']) ? trim($_GET['q']) : '';
$filter_type  = isset($_GET['type']) ? $_GET['type'] : '';
$filter_value = isset($_GET['val'])  ? $_GET['val']  : '';

$query_cols = "id, slug, org_name, county, service_chains, enabling_pillars, challenges_sector,
               role, created_at, personal_email, company_email, phone, personal_phone,
               company_phone, user_type, website, designation, bio, email, org_sector";

// Base WHERE clause
$where_clause = "is_verified = 1 AND role != 'admin' AND IFNULL(is_public, 1) = 1";
$params = [];
$types  = "";

if (!empty($search_query)) {
    $where_clause .= " AND (org_name LIKE ?"
        . " OR bio LIKE ?"
        . " OR email LIKE ?"
        . " OR phone LIKE ?"
        . " OR personal_email LIKE ?"
        . " OR personal_phone LIKE ?"
        . " OR company_email LIKE ?"
        . " OR company_phone LIKE ?"
        . " OR IFNULL(website,'') LIKE ?"
        . " OR IFNULL(designation,'') LIKE ?"
        . " OR county LIKE ?"
        . " OR IFNULL(service_chains,'') LIKE ?"
        . " OR IFNULL(enabling_pillars,'') LIKE ?"
        . " OR IFNULL(challenges_sector,'') LIKE ?)";
    $like_val = "%$search_query%";
    for ($p = 0; $p < 14; $p++) {
        $params[] = $like_val;
        $types   .= "s";
    }
}

if (!empty($filter_type) && !empty($filter_value)) {
    if ($filter_type === 'county') {
        $where_clause .= " AND county LIKE ?";
        $params[] = "%$filter_value%";
        $types   .= "s";
    } elseif (in_array($filter_type, ['service_chains', 'enabling_pillars', 'challenges_sector'])) {
        $where_clause .= " AND JSON_CONTAINS(IFNULL($filter_type, '[]'), JSON_QUOTE(?))";
        $params[] = $filter_value;
        $types   .= "s";
    }
}

// Fetch direct-match users
$query = "SELECT $query_cols, IFNULL(is_public, 1) as is_public_flag, privacy_settings
          FROM users WHERE $where_clause ORDER BY org_name ASC LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
if (!$stmt) {
    $query = "SELECT $query_cols FROM users WHERE $where_clause ORDER BY org_name ASC LIMIT ? OFFSET ?";
    $stmt  = $conn->prepare($query);
}

$users_list  = [];
$total_count = 0;
$total_pages = 1;

if ($stmt) {
    $bind_params   = [];
    $bind_params[] = &$types;
    for ($i = 0; $i < count($params); $i++) {
        $bind_params[] = &$params[$i];
    }
    $types        .= "ii";
    $bind_params[] = &$limit;
    $bind_params[] = &$offset;

    if (strlen($types) > 0) {
        call_user_func_array([$stmt, 'bind_param'], $bind_params);
    }
    $stmt->execute();
    $users_list = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    // Total count
    $count_query = "SELECT COUNT(*) as total FROM users WHERE $where_clause";
    $count_stmt  = $conn->prepare($count_query);
    if ($count_stmt) {
        if (count($params) > 0) {
            $count_types      = substr($types, 0, -2);
            $count_bind       = [];
            $count_bind[]     = &$count_types;
            for ($i = 0; $i < count($params); $i++) {
                $count_bind[] = &$params[$i];
            }
            call_user_func_array([$count_stmt, 'bind_param'], $count_bind);
        }
        $count_stmt->execute();
        $total_count = $count_stmt->get_result()->fetch_assoc()['total'];
        $total_pages = ceil($total_count / $limit);
    }
}

// ── Submission cross-reference (only when searching) ──
$via_sub_users = [];
if (!empty($search_query)) {
    $direct_ids = array_column($users_list, 'id');
    $exclude    = !empty($direct_ids) ? implode(',', array_map('intval', $direct_ids)) : '0';
    $sub_like   = '%' . $conn->real_escape_string($search_query) . '%';

    $sql_sub = "SELECT s.user_id, s.title AS sub_title, s.county AS sub_county,
                       u.id, u.org_name, u.county, u.slug, u.user_type, u.designation,
                       u.service_chains, u.enabling_pillars, u.bio, u.created_at,
                       u.personal_email, u.company_email, u.phone, u.personal_phone, u.company_phone,
                       u.email, u.website, u.org_sector, u.challenges_sector,
                       IFNULL(u.is_public,1) as is_public_flag, u.privacy_settings
                FROM submissions s
                JOIN users u ON s.user_id = u.id
                WHERE s.is_verified = 1
                  AND u.is_verified = 1 AND u.role != 'admin' AND IFNULL(u.is_public,1) = 1
                  AND s.user_id NOT IN ($exclude)
                  AND (s.title LIKE ? OR s.story LIKE ? OR s.org_name LIKE ?
                       OR s.service_chains LIKE ? OR s.enabling_pillars LIKE ?
                       OR s.thematic_categories LIKE ? OR s.county LIKE ?)
                GROUP BY s.user_id
                ORDER BY u.org_name
                LIMIT 12";

    $sub_stmt = $conn->prepare($sql_sub);
    if ($sub_stmt) {
        $sub_stmt->bind_param("sssssss", $sub_like,$sub_like,$sub_like,$sub_like,$sub_like,$sub_like,$sub_like);
        $sub_stmt->execute();
        $sub_res = $sub_stmt->get_result();
        while ($row = $sub_res->fetch_assoc()) {
            $row['_match_reason'] = 'Submitted: "' . htmlspecialchars(mb_substr($row['sub_title'], 0, 60)) . '"';
            $via_sub_users[] = $row;
        }
        $sub_stmt->close();
    }
}

// ── Match-reason helper for direct matches ──
function get_match_reason_html($user, $q) {
    if (empty($q)) return '';
    $q_lower = mb_strtolower($q);
    $checks  = [
        'org_name'          => 'Name matches',
        'bio'               => 'Bio mentions "' . htmlspecialchars($q) . '"',
        'county'            => 'Located in ' . htmlspecialchars($user['county'] ?? ''),
        'designation'       => 'Designation matches',
        'website'           => 'Website matches',
        'email'             => 'Email matches',
        'phone'             => 'Phone matches',
        'personal_email'    => 'Email matches',
        'personal_phone'    => 'Phone matches',
        'company_email'     => 'Email matches',
        'company_phone'     => 'Phone matches',
        'service_chains'    => 'Active in matching service chain',
        'enabling_pillars'  => 'Active in matching enabling pillar',
        'challenges_sector' => 'Works on matching sector challenge',
    ];
    foreach ($checks as $field => $reason) {
        if (!empty($user[$field]) && mb_stripos($user[$field], $q) !== false) {
            return $reason;
        }
    }
    return 'Profile matches';
}

// ── Sector grouping for browse mode ──
function get_user_sector($user) {
    if (!empty($user['org_sector'])) {
        $data = json_decode($user['org_sector'], true);
        if (!empty($data['sector'])) return $data['sector'];
    }
    // Fallback to user_type
    return ($user['user_type'] ?? 'organization') === 'individual' ? 'Individuals' : 'Organizations';
}

// Helper for clean output
function clean_out($text) {
    return htmlspecialchars(html_entity_decode($text ?? '', ENT_QUOTES | ENT_HTML5), ENT_QUOTES | ENT_HTML5);
}

// Group users by sector for browse mode
$sector_groups = [];
if (empty($search_query)) {
    foreach ($users_list as $u) {
        $sector = get_user_sector($u);
        $sector_groups[$sector][] = $u;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Explore Directory | SaniBook Kenya</title>
    <meta name="description"
        content="Explore and connect with organizations and individuals in the Kenyan sanitation sector.">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <link rel="icon" href="images/saniBook logo.png" type="image/png">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'brand-blue': '#002855',
                        'brand-accent': '#00A1E0',
                        'brand-green': '#8cc63f',
                        'brand-teal': '#009688',
                    },
                    fontFamily: {
                        'montserrat': ['Montserrat', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body { font-family: 'Inter', system-ui, sans-serif; }
        .member-card {
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 1rem;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
            transition: all 0.22s ease;
        }
        .member-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
            border-color: #5eead4;
        }
        .line-clamp-2 { display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden; }
        .line-clamp-3 { display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden; }
        .pill { border-radius:9999px;font-size:11px;font-weight:700;padding:3px 10px; }

        /* AJAX dropdown */
        .explore-dropdown {
            position: absolute; top: calc(100% + 6px); left: 0; right: 0; z-index: 50;
            background: #fff; border: 1px solid #e2e8f0; border-radius: 14px;
            box-shadow: 0 12px 40px rgba(15,23,42,0.15);
            max-height: 420px; overflow-y: auto;
        }
        .ed-group-label {
            padding: 8px 16px 4px; font-size: 10px; font-weight: 800;
            text-transform: uppercase; letter-spacing: 0.06em; color: #94a3b8;
            border-bottom: 1px solid #f1f5f9;
        }
        .ed-item {
            display: flex; align-items: center; gap: 10px;
            padding: 10px 16px; text-decoration: none; color: inherit;
            transition: background 0.12s;
        }
        .ed-item:hover { background: #f8fafc; }
        .ed-icon-wrap {
            width: 32px; height: 32px; border-radius: 8px;
            display: flex; align-items: center; justify-content: center;
            font-size: 0.75rem; flex-shrink: 0;
        }
        .ed-reason {
            font-size: 10px; color: #64748b; font-style: italic;
            margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
            max-width: 260px;
        }

        /* Sector header */
        .sector-header {
            display: flex; align-items: center; gap: 10px;
            margin-bottom: 16px; margin-top: 8px;
        }
        .sector-header h3 {
            font-family: 'Montserrat', sans-serif;
            font-weight: 800; font-size: 0.95rem; color: #1e293b;
        }
        .sector-header .count-badge {
            font-size: 10px; font-weight: 800; padding: 2px 8px;
            border-radius: 999px; background: #f1f5f9; color: #64748b;
        }
        .sector-header .line { flex: 1; height: 1px; background: #e2e8f0; }

        /* Match reason badge on cards */
        .match-badge {
            display: inline-flex; align-items: center; gap: 4px;
            font-size: 10px; font-weight: 600; padding: 2px 8px;
            border-radius: 999px; background: #fef3c7; color: #92400e;
            max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
    </style>
</head>

<body class="bg-slate-50 min-h-screen flex flex-col font-sans selection:bg-brand-accent selection:text-white">

    <?php include 'navbar.php'; ?>

    <main class="flex-grow pt-24 pb-20">
        <!-- Header Section -->
        <section class="bg-brand-blue text-white py-16 relative overflow-hidden">
            <div class="absolute inset-0 opacity-10"
                style="background-image: radial-gradient(circle at 2px 2px, white 1px, transparent 0); background-size: 32px 32px;">
            </div>
            <div class="max-w-7xl mx-auto px-4 relative z-10 text-center">
                <div class="inline-flex items-center gap-2 bg-white/10 px-4 py-2 rounded-full mb-6">
                    <i class="fa-solid fa-users text-brand-accent"></i>
                    <span class="text-sm font-bold tracking-wider uppercase">Public Directory</span>
                </div>
                <h1 class="text-3xl md:text-4xl font-montserrat font-black mb-6 tracking-tight">
                    Explore Our <span class="text-brand-accent">Network</span>
                </h1>
                <p class="text-xl text-blue-100 max-w-2xl mx-auto leading-relaxed mb-8">
                    Connect with organizations, innovators, and individuals driving change in the Kenyan sanitation sector.
                </p>

                <!-- Search and Filter Bar -->
                <div class="max-w-4xl mx-auto bg-white rounded-2xl p-2 shadow-lg flex flex-col md:flex-row gap-2">
                    <form action="explore.php" method="GET" class="flex-1 flex flex-col md:flex-row gap-2 w-full" id="exploreSearchForm">
                        <div class="relative flex-1" id="exploreSearchWrap">
                            <i class="fa-solid fa-search absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
                            <input type="text" name="q" id="exploreSearchInput"
                                value="<?= htmlspecialchars($search_query) ?>"
                                placeholder="Search by name, phone, email, website, county, sector..."
                                autocomplete="off"
                                class="w-full pl-10 pr-4 py-3 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-brand-accent text-slate-800">
                            <!-- AJAX dropdown -->
                            <div class="explore-dropdown hidden" id="exploreDropdown"></div>
                        </div>

                        <div class="relative w-full md:w-64">
                            <select name="type" id="filterType"
                                class="w-full pl-4 pr-10 py-3 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-brand-accent appearance-none bg-slate-50 text-slate-700"
                                onchange="updateFilterValues()">
                                <option value="">Filter by Category...</option>
                                <option value="county" <?= $filter_type === 'county' ? 'selected' : '' ?>>County</option>
                                <option value="service_chains" <?= $filter_type === 'service_chains' ? 'selected' : '' ?>>Service Chain</option>
                                <option value="enabling_pillars" <?= $filter_type === 'enabling_pillars' ? 'selected' : '' ?>>Enabling Pillar</option>
                            </select>
                            <i class="fa-solid fa-chevron-down absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none text-sm"></i>
                        </div>

                        <div class="relative w-full md:w-64 <?= empty($filter_type) ? 'hidden' : '' ?>"
                            id="filterValueContainer">
                            <select name="val" id="filterValue"
                                class="w-full pl-4 pr-10 py-3 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-brand-accent appearance-none bg-slate-50 text-slate-700">
                                <option value="">Select Option</option>
                            </select>
                            <i class="fa-solid fa-chevron-down absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none text-sm"></i>
                        </div>

                        <button type="submit"
                            class="px-8 py-3 rounded-xl font-bold transition-colors flex items-center justify-center gap-2 text-white"
                            style="background:linear-gradient(90deg,#008080,#0097a7);">
                            <i class="fa-solid fa-magnifying-glass"></i> Search
                        </button>

                        <?php if (!empty($search_query) || !empty($filter_type)): ?>
                            <a href="explore.php"
                                class="bg-slate-100 text-slate-600 px-6 py-3 rounded-xl font-bold hover:bg-slate-200 transition-colors flex items-center justify-center whitespace-nowrap">
                                <i class="fa-solid fa-xmark mr-1"></i> Clear
                            </a>
                        <?php endif; ?>
                    </form>
                </div>

                <?php if (!$is_logged_in): ?>
                    <div class="mt-6 bg-white/10 p-3 rounded-xl inline-flex items-center gap-2 text-sm border border-white/20">
                        <i class="fa-solid fa-lock text-teal-300"></i>
                        Register or login to view contact details and connect directly with members.
                    </div>
                <?php endif; ?>
            </div>
        </section>

        <!-- Dynamic Filter Script -->
        <script>
            const filterOptions = {
                'county': ["Mombasa","Kwale","Kilifi","Tana River","Lamu","Taita Taveta","Garissa","Wajir","Mandera","Marsabit","Isiolo","Meru","Tharaka-Nithi","Embu","Kitui","Machakos","Makueni","Nyandarua","Nyeri","Kirinyaga","Murang'a","Kiambu","Turkana","West Pokot","Samburu","Trans-Nzoia","Uasin Gishu","Elgeyo-Marakwet","Nandi","Baringo","Laikipia","Nakuru","Narok","Kajiado","Kericho","Bomet","Kakamega","Vihiga","Bungoma","Busia","Siaya","Kisumu","Homa Bay","Migori","Kisii","Nyamira","Nairobi"],
                'service_chains': ["Capture & Containment","Emptying & Transport","Treatment & Disposal","Reuse & Circular Economy"],
                'enabling_pillars': ["Financing","Governance","Research & Learning","Collaboration","Menstrual Health Management","Capacity Building"]
            };
            const currentFilterVal = <?= json_encode($filter_value) ?>;

            function updateFilterValues() {
                const typeSelect = document.getElementById('filterType');
                const valContainer = document.getElementById('filterValueContainer');
                const valSelect = document.getElementById('filterValue');
                const type = typeSelect.value;
                if (type && filterOptions[type]) {
                    valSelect.innerHTML = '<option value="">Select Option</option>';
                    filterOptions[type].forEach(opt => {
                        const selected = opt === currentFilterVal ? 'selected' : '';
                        valSelect.innerHTML += `<option value="${opt}" ${selected}>${opt}</option>`;
                    });
                    valContainer.classList.remove('hidden');
                } else {
                    valContainer.classList.add('hidden');
                    valSelect.innerHTML = '<option value="">Select Option</option>';
                }
            }
            document.addEventListener('DOMContentLoaded', updateFilterValues);
        </script>

        <!-- Directory Grid -->
        <section class="max-w-7xl mx-auto px-4 py-12">

            <?php if (empty($users_list) && empty($via_sub_users)): ?>
                <!-- Empty state -->
                <div class="text-center py-20 bg-white rounded-2xl shadow-sm border border-slate-200">
                    <div class="w-20 h-20 bg-teal-50 text-teal-400 rounded-full flex items-center justify-center mx-auto mb-6">
                        <i class="fa-solid fa-users-slash text-3xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-slate-800 mb-2 font-montserrat">No Members Found</h3>
                    <p class="text-slate-500 max-w-md mx-auto text-sm">
                        <?php if (!empty($search_query)): ?>
                            No results for "<strong><?= htmlspecialchars($search_query) ?></strong>". Try different keywords.
                        <?php else: ?>
                            There are currently no public members matching your criteria.
                        <?php endif; ?>
                    </p>
                    <a href="explore.php" class="inline-block mt-4 px-5 py-2 rounded-lg text-sm font-bold text-white"
                        style="background:linear-gradient(90deg,#008080,#0097a7);">Clear Filters</a>
                </div>

            <?php elseif (!empty($search_query)): ?>
                <!-- ═══ SEARCH MODE: grouped results with match reasons ═══ -->
                <div class="mb-6">
                    <p class="text-sm text-slate-500">
                        <strong><?= $total_count + count($via_sub_users) ?></strong> results for
                        "<strong><?= htmlspecialchars($search_query) ?></strong>"
                    </p>
                </div>

                <?php if (!empty($users_list)): ?>
                <div class="sector-header">
                    <i class="fa-solid fa-bullseye text-blue-500"></i>
                    <h3>Direct Profile Matches</h3>
                    <span class="count-badge"><?= count($users_list) ?></span>
                    <div class="line"></div>
                </div>
                <div class="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
                    <?php foreach ($users_list as $user):
                        $reason = get_match_reason_html($user, $search_query);
                        include __DIR__ . '/_explore_card.php';
                    endforeach; ?>
                </div>
                <?php endif; ?>

                <?php if (!empty($via_sub_users)): ?>
                <div class="sector-header">
                    <i class="fa-solid fa-file-lines text-teal-500"></i>
                    <h3>Related via Submissions</h3>
                    <span class="count-badge"><?= count($via_sub_users) ?></span>
                    <div class="line"></div>
                </div>
                <p class="text-xs text-slate-400 mb-4 -mt-2">
                    These members didn't directly match, but have submitted data related to your search.
                </p>
                <div class="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
                    <?php foreach ($via_sub_users as $user):
                        $reason = $user['_match_reason'] ?? '';
                        include __DIR__ . '/_explore_card.php';
                    endforeach; ?>
                </div>
                <?php endif; ?>

            <?php elseif (!empty($sector_groups)): ?>
                <!-- ═══ BROWSE MODE: grouped by sector ═══ -->
                <?php
                // Sector icon/color map
                $sector_meta = [
                    'Public Sector'          => ['icon' => 'fa-landmark',     'color' => '#1d4ed8'],
                    'Private Sector'         => ['icon' => 'fa-briefcase',    'color' => '#0f766e'],
                    'Civil Society & NGOs'   => ['icon' => 'fa-hand-holding-heart', 'color' => '#9333ea'],
                    'Financial Institutions' => ['icon' => 'fa-coins',        'color' => '#b45309'],
                    'Research & Academic'    => ['icon' => 'fa-graduation-cap','color' => '#0369a1'],
                    'The Users'              => ['icon' => 'fa-people-group', 'color' => '#059669'],
                    'Individuals'            => ['icon' => 'fa-user',         'color' => '#7c3aed'],
                    'Organizations'          => ['icon' => 'fa-building',     'color' => '#334155'],
                    'Others'                 => ['icon' => 'fa-ellipsis',     'color' => '#64748b'],
                ];
                foreach ($sector_groups as $sector_name => $sector_users):
                    $meta = $sector_meta[$sector_name] ?? ['icon' => 'fa-folder', 'color' => '#64748b'];
                ?>
                <div class="sector-header">
                    <span class="w-8 h-8 rounded-lg flex items-center justify-center" style="background:<?= $meta['color'] ?>15">
                        <i class="fa-solid <?= $meta['icon'] ?>" style="color:<?= $meta['color'] ?>;font-size:0.8rem"></i>
                    </span>
                    <h3><?= htmlspecialchars($sector_name) ?></h3>
                    <span class="count-badge"><?= count($sector_users) ?></span>
                    <div class="line"></div>
                </div>
                <div class="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-10">
                    <?php foreach ($sector_users as $user):
                        $reason = '';
                        include __DIR__ . '/_explore_card.php';
                    endforeach; ?>
                </div>
                <?php endforeach; ?>

            <?php else: ?>
                <!-- Flat grid fallback (filter active but no search) -->
                <div class="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <?php foreach ($users_list as $user):
                        $reason = '';
                        include __DIR__ . '/_explore_card.php';
                    endforeach; ?>
                </div>
            <?php endif; ?>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="mt-16 flex justify-center items-center gap-2">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?= $page - 1 ?><?= !empty($search_query) ? '&q=' . urlencode($search_query) : '' ?><?= !empty($filter_type) ? '&type=' . urlencode($filter_type) : '' ?><?= !empty($filter_value) ? '&val=' . urlencode($filter_value) : '' ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:border-brand-accent hover:text-brand-accent transition-all">
                            <i class="fa-solid fa-chevron-left text-sm"></i>
                        </a>
                    <?php endif; ?>

                    <?php
                    $start = max(1, $page - 2);
                    $end   = min($total_pages, $page + 2);
                    $qs    = "";
                    if (!empty($search_query)) $qs .= "&q=" . urlencode($search_query);
                    if (!empty($filter_type))  $qs .= "&type=" . urlencode($filter_type);
                    if (!empty($filter_value)) $qs .= "&val=" . urlencode($filter_value);

                    if ($start > 1) {
                        echo '<a href="?page=1' . $qs . '" class="w-10 h-10 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:border-brand-accent hover:text-brand-accent transition-all font-medium">1</a>';
                        if ($start > 2) echo '<span class="px-2 text-slate-400">...</span>';
                    }
                    for ($i = $start; $i <= $end; $i++) {
                        $ac = $i === $page
                            ? 'bg-brand-blue text-white shadow-md border-brand-blue'
                            : 'border-slate-200 text-slate-600 hover:border-brand-accent hover:text-brand-accent';
                        echo '<a href="?page=' . $i . $qs . '" class="w-10 h-10 flex items-center justify-center rounded-lg border transition-all font-medium ' . $ac . '">' . $i . '</a>';
                    }
                    if ($end < $total_pages) {
                        if ($end < $total_pages - 1) echo '<span class="px-2 text-slate-400">...</span>';
                        echo '<a href="?page=' . $total_pages . $qs . '" class="w-10 h-10 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:border-brand-accent hover:text-brand-accent transition-all font-medium">' . $total_pages . '</a>';
                    }
                    ?>

                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?= $page + 1 ?><?= !empty($search_query) ? '&q=' . urlencode($search_query) : '' ?><?= !empty($filter_type) ? '&type=' . urlencode($filter_type) : '' ?><?= !empty($filter_value) ? '&val=' . urlencode($filter_value) : '' ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:border-brand-accent hover:text-brand-accent transition-all">
                            <i class="fa-solid fa-chevron-right text-sm"></i>
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

        </section>
    </main>

    <?php include 'footer.php'; ?>

    <!-- ═══ AJAX Search Dropdown ═══ -->
    <script>
    (function() {
        const input    = document.getElementById('exploreSearchInput');
        const dropdown = document.getElementById('exploreDropdown');
        if (!input || !dropdown) return;

        let timer = null;

        const typeLabels = {
            direct_org:        'Organizations',
            direct_individual: 'Individuals',
            via_submission:    'Related via Submissions'
        };
        const typeOrder = ['direct_org', 'direct_individual', 'via_submission'];
        const typeMeta = {
            direct_org:        { bg: '#eff6ff', fg: '#2563eb', icon: 'fa-building' },
            direct_individual: { bg: '#faf5ff', fg: '#7c3aed', icon: 'fa-user' },
            via_submission:    { bg: '#f0fdf4', fg: '#0d9488', icon: 'fa-file-lines' }
        };

        input.addEventListener('input', function() {
            clearTimeout(timer);
            const q = this.value.trim();
            if (q.length < 2) { dropdown.classList.add('hidden'); return; }

            timer = setTimeout(() => {
                fetch('/api/explore-search.php?q=' + encodeURIComponent(q))
                    .then(r => r.json())
                    .then(data => {
                        const items = data.results || [];
                        if (!items.length) { dropdown.classList.add('hidden'); return; }

                        // Group by type
                        const grouped = {};
                        items.forEach(item => {
                            if (!grouped[item.type]) grouped[item.type] = [];
                            grouped[item.type].push(item);
                        });

                        let html = '';
                        typeOrder.forEach(type => {
                            if (!grouped[type]) return;
                            html += `<div class="ed-group-label">${typeLabels[type] || type}</div>`;
                            grouped[type].forEach(item => {
                                const meta = typeMeta[item.type] || typeMeta.direct_org;
                                html += `<a href="${item.url}" class="ed-item">
                                    <span class="ed-icon-wrap" style="background:${meta.bg}">
                                        <i class="fa-solid ${meta.icon}" style="color:${meta.fg}"></i>
                                    </span>
                                    <div class="min-w-0 flex-1">
                                        <p style="font-size:0.825rem;font-weight:600;color:#1e293b;line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:280px">${item.title}</p>
                                        ${item.sub ? `<p style="font-size:0.7rem;color:#94a3b8;margin-top:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:260px">${item.sub}</p>` : ''}
                                        ${item.reason ? `<p class="ed-reason"><i class="fa-solid fa-lightbulb" style="color:#f59e0b;margin-right:3px"></i>${item.reason}</p>` : ''}
                                    </div>
                                </a>`;
                            });
                        });

                        // Footer
                        html += `<a href="/explore.php?q=${encodeURIComponent(q)}" style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px 16px;border-top:1px solid #e2e8f0;font-size:0.75rem;font-weight:700;color:#2563eb;text-decoration:none;border-radius:0 0 14px 14px;background:#f8fafc;transition:background .15s" onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#f8fafc'">
                            <i class="fa-solid fa-magnifying-glass" style="font-size:0.65rem"></i> View all results for &ldquo;${q}&rdquo;
                        </a>`;

                        dropdown.innerHTML = html;
                        dropdown.classList.remove('hidden');
                    })
                    .catch(() => dropdown.classList.add('hidden'));
            }, 300);
        });

        // Close dropdown on outside click
        document.addEventListener('click', function(e) {
            if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });

        // Focus shows dropdown if it has content
        input.addEventListener('focus', function() {
            if (dropdown.innerHTML.trim()) dropdown.classList.remove('hidden');
        });
    })();
    </script>

</body>
</html>