<?php

/**
 * legislatif.php - Halaman untuk menampilkan daftar anggota legislatif
 * 
 * File ini berfungsi untuk menampilkan daftar anggota legislatif dari seluruh Indonesia
 * termasuk DPR-RI, DPD-RI, DPRD Provinsi dan DPRD Kabupaten/Kota.
 * 
 * Fitur:
 * - Pencarian berdasarkan nama
 * - Filter berdasarkan instansi, partai, dan dapil
 * - Pagination untuk navigasi hasil
 * - Tampilan responsif untuk desktop dan mobile
 * 
 * @author pejabat.id
 * @version 2.0
 */

// ============================================================================
// KONFIGURASI & INISIALISASI
// ============================================================================

// Aktifkan strict error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Nonaktifkan tampilan error untuk production

// Include file yang dibutuhkan
require_once 'utils.php';
require_once 'db-config.php';

// Koneksi ke database
$conn = getDbConnection();
if (!$conn) {
    logError("Koneksi database gagal");
    renderErrorPage("Koneksi database gagal. Silakan coba lagi nanti.");
    exit;
}

// ============================================================================
// DEFINISI FUNGSI
// ============================================================================

/**
 * Mencatat pesan error ke log
 * 
 * @param string $message Pesan error yang akan dicatat
 * @return void
 */
function logError($message)
{
    error_log("[" . date('Y-m-d H:i:s') . "] " . $message);
}

/**
 * Menampilkan halaman error dengan pesan yang ramah
 * 
 * @param string $message Pesan error yang akan ditampilkan
 * @return void
 */
function renderErrorPage($message)
{
    echo '<div class="error-message">';
    echo '⚠️ ' . htmlspecialchars($message);
    echo '</div>';
}

/**
 * Sanitasi input dari pengguna
 * 
 * @param mysqli $conn Koneksi database
 * @param string $input Input yang akan disanitasi
 * @return string Input yang sudah disanitasi
 */
function sanitizeInput($conn, $input)
{
    if (empty($input)) {
        return '';
    }

    // Sanitasi dengan mysqli real_escape_string dan strip_tags
    $sanitized = $conn->real_escape_string(strip_tags(trim($input)));
    return $sanitized;
}

/**
 * Mengambil parameter dari $_GET dengan sanitasi
 * 
 * @param mysqli $conn Koneksi database
 * @param string $paramName Nama parameter
 * @param string $default Nilai default
 * @param bool $numeric Apakah parameter harus berupa angka
 * @return string|int Parameter yang sudah disanitasi
 */
function getParam($conn, $paramName, $default = '', $numeric = false)
{
    if (!isset($_GET[$paramName])) {
        return $default;
    }

    $value = sanitizeInput($conn, $_GET[$paramName]);

    if ($numeric) {
        if (!is_numeric($value)) {
            return $default;
        }
        return (int)$value;
    }

    return $value;
}

/**
 * Membuat SQL UNION query untuk menggabungkan data dari semua tabel
 * 
 * @param mysqli $conn Koneksi database
 * @param array $tables Array berisi nama tabel yang akan digabungkan
 * @param array $activeTables Array berisi nama tabel yang aktif (sesuai filter)
 * @return string Query SQL
 */
function buildUnionQuery($conn, $tables, $activeTables)
{
    $sql = "";
    $unionClause = "";

    foreach ($activeTables as $table) {
        // Periksa apakah tabel ada dalam database
        $tableExistsQuery = "SHOW TABLES LIKE '" . sanitizeInput($conn, $table) . "'";
        $tableExistsResult = $conn->query($tableExistsQuery);

        if ($tableExistsResult && $tableExistsResult->num_rows > 0) {
            $sql .= $unionClause;

            if ($table === 'dpdri') {
                // Untuk dpdri, gunakan suara sebagai pengganti logo_partai
                $sql .= "(SELECT id, nama, instansi, instansi_daerah, dapil, suara as logo_partai, 
                        partai, jenis_kelamin, agama, foto_pejabat, logo_instansi, 
                        '$table' as table_source FROM $table)";
            } else {
                $sql .= "(SELECT id, nama, instansi, instansi_daerah, dapil, logo_partai, 
                        partai, jenis_kelamin, agama, foto_pejabat, logo_instansi, 
                        '$table' as table_source FROM $table)";
            }

            $unionClause = " UNION ALL ";
        }
    }

    // Jika tidak ada tabel ditemukan, buat query kosong
    if (empty($sql)) {
        $sql = "SELECT 0 as id, '' as nama, '' as instansi, '' as instansi_daerah, 
                '' as dapil, '' as logo_partai, '' as partai, '' as jenis_kelamin, 
                '' as agama, '' as foto_pejabat, '' as logo_instansi, '' as table_source 
                FROM DUAL LIMIT 0";
    }

    return $sql;
}

/**
 * Membangun SQL WHERE clause berdasarkan filter dan pencarian
 * 
 * @param mysqli $conn Koneksi database
 * @param string $searchKeyword Kata kunci pencarian
 * @param string $filterPartai Filter partai
 * @param string $filterDapil Filter dapil
 * @return array Array berisi WHERE conditions dan pesan error
 */
function buildWhereConditions($conn, $searchKeyword, $filterPartai, $filterDapil)
{
    $whereConditions = [];
    $error = null;

    // Tambahkan kondisi pencarian dengan sanitasi input
    if (!empty($searchKeyword)) {
        $safeSearchKeyword = sanitizeInput($conn, $searchKeyword);
        $whereConditions[] = "nama LIKE '%{$safeSearchKeyword}%'";
    }

    // Tambahkan kondisi filter partai dengan sanitasi input
    if (!empty($filterPartai)) {
        $safeFilterPartai = sanitizeInput($conn, $filterPartai);
        $whereConditions[] = "partai = '{$safeFilterPartai}'";
    }

    // Tambahkan kondisi filter dapil
    if (!empty($filterDapil)) {
        $safeFilterDapil = sanitizeInput($conn, $filterDapil);
        $whereConditions[] = "dapil = '{$safeFilterDapil}'";
    }

    return ['conditions' => $whereConditions, 'error' => $error];
}

/**
 * Menghitung total data berdasarkan query dan filter
 * 
 * @param mysqli $conn Koneksi database
 * @param string $baseQuery Query dasar
 * @param array $whereConditions Array berisi kondisi WHERE
 * @return int Jumlah total data
 */
function countTotalData($conn, $baseQuery, $whereConditions)
{
    try {
        $countQuery = "SELECT * FROM ($baseQuery) AS combined";

        // Jika ada kondisi, tambahkan ke query
        if (!empty($whereConditions)) {
            $countQuery .= " WHERE " . implode(" AND ", $whereConditions);
        }

        $totalDataQuery = "SELECT COUNT(*) as total FROM ($countQuery) as count_table";
        $totalDataResult = $conn->query($totalDataQuery);

        if (!$totalDataResult) {
            throw new Exception("Query error: " . $conn->error);
        }

        return $totalDataResult->fetch_assoc()['total'];
    } catch (Exception $e) {
        logError("Error saat menghitung total data: " . $e->getMessage());
        return 0;
    }
}

/**
 * Mendapatkan daftar opsi dapil berdasarkan instansi
 * 
 * @param mysqli $conn Koneksi database
 * @param string $filterInstansi Instansi yang dipilih
 * @return array Array berisi opsi dapil
 */
function getDapilOptions($conn, $filterInstansi)
{
    $dapilOptions = [];

    if (empty($filterInstansi)) {
        return $dapilOptions;
    }

    try {
        $safeFilterInstansi = sanitizeInput($conn, $filterInstansi);
        $dapilQuery = "SELECT DISTINCT dapil FROM $safeFilterInstansi WHERE dapil IS NOT NULL AND dapil != '' ORDER BY dapil";
        $dapilResult = $conn->query($dapilQuery);

        if ($dapilResult && $dapilResult->num_rows > 0) {
            while ($dapilRow = $dapilResult->fetch_assoc()) {
                $dapilOptions[] = $dapilRow['dapil'];
            }
        }
    } catch (Exception $e) {
        logError("Error saat mengambil daftar dapil: " . $e->getMessage());
    }

    return $dapilOptions;
}

/**
 * Mendapatkan data partai dan logo untuk dropdown filter
 * 
 * @param mysqli $conn Koneksi database
 * @param array $tables Array berisi nama tabel yang akan diproses
 * @return array Array berisi partai dan logo
 */
function getPartyData($conn, $tables)
{
    $partyLogos = [];
    $sortedParties = [];

    // Kecualikan DPD dari daftar tabel
    $nonDpdTables = array_diff($tables, ['dpdri']);

    try {
        // Dapatkan logo partai
        foreach ($nonDpdTables as $table) {
            $tableExistsQuery = "SHOW TABLES LIKE '" . sanitizeInput($conn, $table) . "'";
            $tableExistsResult = $conn->query($tableExistsQuery);

            if ($tableExistsResult && $tableExistsResult->num_rows > 0) {
                $logoQuery = "SELECT DISTINCT partai, logo_partai FROM $table 
                            WHERE partai IS NOT NULL AND partai != '' AND 
                            logo_partai IS NOT NULL AND logo_partai != ''";
                $logoResult = $conn->query($logoQuery);

                if ($logoResult && $logoResult->num_rows > 0) {
                    while ($logoRow = $logoResult->fetch_assoc()) {
                        if (!isset($partyLogos[$logoRow['partai']])) {
                            $partyLogos[$logoRow['partai']] = $logoRow['logo_partai'];
                        }
                    }
                }
            }
        }

        // Dapatkan daftar partai unik
        $parties = [];
        $partaiQuery = "SELECT DISTINCT partai FROM (";
        $partyClauses = [];

        foreach ($nonDpdTables as $table) {
            $tableExistsQuery = "SHOW TABLES LIKE '" . sanitizeInput($conn, $table) . "'";
            $tableExistsResult = $conn->query($tableExistsQuery);

            if ($tableExistsResult && $tableExistsResult->num_rows > 0) {
                $partyClauses[] = "(SELECT partai FROM $table WHERE partai IS NOT NULL AND partai != '')";
            }
        }

        if (!empty($partyClauses)) {
            $partaiQuery .= implode(" UNION ", $partyClauses);
            $partaiQuery .= ") AS partai_list";

            $partaiResult = $conn->query($partaiQuery);

            if ($partaiResult && $partaiResult->num_rows > 0) {
                while ($partaiRow = $partaiResult->fetch_assoc()) {
                    if (!empty($partaiRow['partai'])) {
                        $parties[] = $partaiRow['partai'];
                    }
                }

                // Tentukan urutan yang diinginkan (urutan yang sudah ditentukan untuk partai)
                $partyOrder = [
                    'PKB',
                    'GERINDRA',
                    'PDI-P',
                    'GOLKAR',
                    'NASDEM',
                    'BURUH',
                    'GELORA',
                    'PKS',
                    'PKN',
                    'HANURA',
                    'GARUDA',
                    'PAN',
                    'PBB',
                    'DEMOKRAT',
                    'PSI',
                    'PERINDO',
                    'PPP',
                    'PNA',
                    'GABTHAT',
                    'PDA',
                    'PA',
                    'PAS',
                    'SIRA',
                    'UMMAT'
                ];

                // Urutkan partai sesuai dengan urutan yang ditentukan
                $sortedParties = [];

                // Pertama, tambahkan partai yang ada dalam daftar urutan
                foreach ($partyOrder as $party) {
                    if (in_array($party, $parties)) {
                        $sortedParties[] = $party;
                    }
                }

                // Kemudian tambahkan partai lainnya secara alfabetis
                $remainingParties = array_diff($parties, $sortedParties);
                sort($remainingParties);
                $sortedParties = array_merge($sortedParties, $remainingParties);
            }
        }
    } catch (Exception $e) {
        logError("Error saat mengambil daftar partai: " . $e->getMessage());
    }

    return ['logos' => $partyLogos, 'parties' => $sortedParties];
}

/**
 * Eksekusi query data legislatif dengan pagination dan filter
 * 
 * @param mysqli $conn Koneksi database
 * @param string $unionQuery Query UNION
 * @param array $whereConditions Array berisi kondisi WHERE
 * @param int $limit Jumlah data per halaman
 * @param int $offset Offset paginasi
 * @return array|null Array data legislatif atau null jika gagal
 */
function getLegislativeData($conn, $unionQuery, $whereConditions, $limit, $offset)
{
    try {
        $mainQuery = "SELECT * FROM ($unionQuery) AS combined";

        // Jika ada kondisi, tambahkan ke query
        if (!empty($whereConditions)) {
            $mainQuery .= " WHERE " . implode(" AND ", $whereConditions);
        }

        // Tambahkan pagination
        $mainQuery .= " LIMIT $limit OFFSET $offset";

        $result = $conn->query($mainQuery);

        if (!$result) {
            throw new Exception("Query error: " . $conn->error);
        }

        $data = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }

        return $data;
    } catch (Exception $e) {
        logError("Error saat mengambil data legislatif: " . $e->getMessage());
        return null;
    }
}

/**
 * Render filter dropdown untuk partai dengan logo
 * 
 * @param array $partyData Data partai dan logo
 * @param string $filterPartai Partai yang dipilih
 * @return string HTML untuk dropdown partai
 */
function renderPartyDropdown($partyData, $filterPartai)
{
    $html = '<option value="">PARTAI</option>';

    foreach ($partyData['parties'] as $party) {
        $logoUrl = isset($partyData['logos'][$party]) ? $partyData['logos'][$party] : '';

        $html .= '<option value="' . htmlspecialchars($party) . '"';
        if ($filterPartai == $party) {
            $html .= ' selected';
        }
        if (!empty($logoUrl)) {
            $html .= ' data-logo="' . htmlspecialchars($logoUrl) . '"';
        }
        $html .= '>' . htmlspecialchars($party) . '</option>';
    }

    return $html;
}

/**
 * Render hasil pencarian dalam format tabel
 * 
 * @param array $data Data hasil pencarian
 * @param mysqli $conn Koneksi database
 * @param string $searchKeyword Kata kunci pencarian
 * @return string HTML untuk tabel hasil
 */
function renderLegislativeTable($data, $conn, $searchKeyword)
{
    if (empty($data)) {
        return '';
    }

    $html = '<div class="table-container">';
    $html .= '<div class="button-profil">';
    $html .= '<table>';
    $html .= '<tr>
                <td></td>
                <td>Nama</td>
                <td class="instansi-column">Instansi/Dapil</td>
                <td>Partai</td>
                <td></td>
              </tr>';

    foreach ($data as $row) {
        // Buat slug unik untuk legislator ini
        $nameSlug = createUniqueSlug($conn, $row["nama"], $row["table_source"], $row["id"]);
        $nameSlug = urlencode($nameSlug); // URL encode untuk keamanan
        $tableSource = $row["table_source"];
        $profileUrl = "profil/" . $nameSlug;

        $html .= '<tr>';

        // Tampilkan foto (kini berfungsi sebagai link di mobile)
        $html .= '<th>';
        $html .= '<a href="' . $profileUrl . '" class="mobile-link mobile-photo-link">';
        $html .= '<img class="zoom-effect legislator-photo" src="' . htmlspecialchars($row['foto_pejabat']) . '" width="55" height="75" alt="' . htmlspecialchars($row["nama"]) . '">';
        $html .= '</a>';
        $html .= '<img class="zoom-effect legislator-photo desktop-photo" src="' . htmlspecialchars($row['foto_pejabat']) . '" width="55" height="75" alt="' . htmlspecialchars($row["nama"]) . '">';
        $html .= '</th>';

        // Tampilkan nama dengan highlight jika sesuai keyword pencarian (kini berfungsi sebagai link di mobile)
        $displayName = htmlspecialchars($row["nama"]);
        if (!empty($searchKeyword) && stripos($row["nama"], $searchKeyword) !== false) {
            $displayName = preg_replace('/(' . preg_quote($searchKeyword, '/') . ')/i', '<span class="highlight">$1</span>', $displayName);
        }

        $html .= '<th>';
        $html .= '<a href="' . $profileUrl . '" class="mobile-link mobile-name-link">' . $displayName . '</a>';
        $html .= '<span class="desktop-name">' . $displayName . '</span>';
        $html .= '</th>';

        // Informasi instansi dan dapil
        $instansi = htmlspecialchars($row["instansi"]);
        $instansi_daerah = htmlspecialchars($row["instansi_daerah"]);
        $combined = trim($instansi . " " . $instansi_daerah);

        // Ambil dapil tanpa highlighting
        $dapil = htmlspecialchars($row["dapil"]);

        // Tampilkan instansi dengan warna sesuai tipe
        $html .= '<th class="instansi-column">';
        if ($tableSource == 'dprri' || strpos(strtoupper($combined), 'DPR RI') !== false || strpos(strtoupper($combined), 'DPR-RI') !== false) {
            // DPR RI - Pusat (Kuning terang)
            $html .= '<span style="background: linear-gradient(to right, #fef301, #d9cb00); color: black; padding: 5px 10px; border-radius: 6px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">' . $combined . '</span>';
        } elseif ($tableSource == 'dpdri' || strpos(strtoupper($combined), 'DPD') !== false) {
            // DPD RI - Pusat (Merah terang)
            $html .= '<span style="background: linear-gradient(to right, #dc0000, #a30000); color: white; padding: 5px 10px; border-radius: 6px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">' . $combined . '</span>';
        } elseif ($tableSource == 'dprdprov' || strpos(strtoupper($instansi_daerah), 'PROVINSI') !== false) {
            // DPRD Provinsi - Daerah (Biru lebih gelap)
            $html .= '<span style="background: linear-gradient(to right, #0056b3, #003e80); color: white; padding: 5px 10px; border-radius: 6px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">' . $combined . '</span>';
        } elseif ($tableSource == 'dprdkabko' || strpos(strtoupper($instansi_daerah), 'KOTA') !== false || strpos(strtoupper($instansi_daerah), 'KABUPATEN') !== false) {
            // DPRD Kabupaten/Kota - Daerah (Hijau lebih gelap)
            $html .= '<span style="background: linear-gradient(to right, #218838, #166628); color: white; padding: 5px 10px; border-radius: 6px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">' . $combined . '</span>';
        } else {
            // Default
            $html .= '<span style="background: linear-gradient(to right, #f0f0f0, #dcdcdc); color: #333; padding: 5px 10px; border-radius: 6px; font-weight: bold;">' . $combined . '</span>';
        }

        // Tampilkan informasi dapil
        if (!empty($row["dapil"])) {
            $html .= '<div class="dapil-info"><span class="dapil-text">' . $dapil . '</span></div>';
        }

        $html .= '</th>';

        // Logo partai dengan tooltip (hanya untuk non-DPD)
        if ($tableSource == 'dpdri') {
            $html .= '<th></th>'; // Sel kosong untuk dpdri
        } else {
            $partyName = htmlspecialchars($row["partai"]);
            $html .= '<th>
                    <div class="party-logo-container">
                        <img src="' . htmlspecialchars($row['logo_partai']) . '" 
                            width="40" height="40" 
                            alt="' . $partyName . '">
                        <div class="party-tooltip">' . $partyName . '</div>
                    </div>
                </th>';
        }

        // Tombol profil yang responsif (hanya tampil di desktop)
        $html .= '<th class="profile-btn-cell">
                    <a href="' . $profileUrl . '" class="profile-link">
                        <button type="profil" class="desktop-profile-btn">Profil</button>
                    </a>
                  </th>';
        $html .= '</tr>';
    }

    $html .= '</table>';
    $html .= '</div>';
    $html .= '</div>';

    return $html;
}

/**
 * Render pagination untuk navigasi halaman
 * 
 * @param int $page Halaman saat ini
 * @param int $totalPages Total halaman
 * @param string $searchKeyword Kata kunci pencarian
 * @param string $filterPartai Filter partai
 * @param string $filterInstansi Filter instansi
 * @param string $filterDapil Filter dapil
 * @return string HTML untuk pagination
 */
function renderPagination($page, $totalPages, $searchKeyword, $filterPartai, $filterInstansi, $filterDapil)
{
    if ($totalPages <= 1) {
        return '';
    }

    $html = '<div class="pagination-container">';
    $html .= '<div class="pagination">';
    $html .= 'Halaman ' . $page . ' dari ' . $totalPages . ' &nbsp;';

    // Bangun string parameter filter
    $filterParams = '';
    if (!empty($searchKeyword)) {
        $filterParams .= '&search=' . urlencode($searchKeyword);
    }
    if (!empty($filterPartai)) {
        $filterParams .= '&partai=' . urlencode($filterPartai);
    }
    if (!empty($filterInstansi)) {
        $filterParams .= '&instansi=' . urlencode($filterInstansi);
    }
    if (!empty($filterDapil)) {
        $filterParams .= '&dapil=' . urlencode($filterDapil);
    }

    // Tombol halaman sebelumnya
    if ($page > 1) {
        $html .= '<a href="?page=' . ($page - 1) . $filterParams . '">';
        $html .= '<i class="fas fa-chevron-left"></i>';
        $html .= '</a>';
    }

    // Nomor halaman
    $maxPagesToShow = 5;
    $half = floor($maxPagesToShow / 2);

    // Hitung halaman awal dan akhir
    $startPage = max(1, $page - $half);
    $endPage = min($totalPages, $startPage + $maxPagesToShow - 1);

    // Sesuaikan halaman awal jika diperlukan
    if ($endPage - $startPage + 1 < $maxPagesToShow) {
        $startPage = max(1, $endPage - $maxPagesToShow + 1);
    }

    // Render link halaman
    for ($i = $startPage; $i <= $endPage; $i++) {
        $pageClass = 'page-number';
        if ($page == $i) {
            $pageClass .= ' active';
        }
        // Tambahkan class untuk halaman di sekitar halaman aktif
        if ($i == $page - 1 || $i == $page + 1) {
            $pageClass .= ' active-adjacent';
        }

        $html .= '<a href="?page=' . $i . $filterParams . '" class="' . $pageClass . '">';
        $html .= $i;
        $html .= '</a>';
    }

    // Tombol halaman berikutnya
    if ($page < $totalPages) {
        $html .= '<a href="?page=' . ($page + 1) . $filterParams . '">';
        $html .= '<i class="fas fa-chevron-right"></i>';
        $html .= '</a>';
    }

    $html .= '</div>';
    $html .= '</div>';

    return $html;
}

/**
 * Render pesan "Tidak Ada Hasil" sesuai konteks
 * 
 * @param string $searchKeyword Kata kunci pencarian
 * @param bool $isSearchMode Flag apakah dalam mode pencarian
 * @param bool $isFilterMode Flag apakah dalam mode filter
 * @return string HTML untuk pesan tidak ada hasil
 */
function renderNoResults($searchKeyword, $isSearchMode, $isFilterMode)
{
    $html = '';

    if ($isSearchMode) {
        $html .= '<div class="no-results">';
        $html .= '<i class="fas fa-search"></i>';
        $html .= '<h2>"' . htmlspecialchars($searchKeyword) . '" tidak ditemukan</h2>';
        $html .= '<div class="feedback-button">';
        $html .= '<a href="legislatif.php" class="feedback-link">Cari pejabat legislatif lainnya..</a>';
        $html .= '</div>';
        $html .= '</div>';
    } else if ($isFilterMode) {
        $html .= '<div class="no-results">';
        $html .= '<i class="fa-solid fa-circle-question"></i>';
        $html .= '<h2>Data tidak ditemukan</h2>';
        $html .= '<div class="feedback-button">';
        $html .= '<a href="legislatif.php" class="feedback-link">Reset Filter</a>';
        $html .= '</div>';
        $html .= '</div>';
    } else {
        $html .= '<div class="no-results">';
        $html .= '<i class="fas fa-exclamation-circle"></i>';
        $html .= '<h2>Belum ada data</h2>';
        $html .= '<p>Saat ini belum ada data anggota legislatif yang tersedia.</p>';
        $html .= '</div>';
    }

    return $html;
}

// ============================================================================
// PEMROSESAN UTAMA
// ============================================================================

// Array tabel yang akan ditampilkan dalam urutan yang diminta
$tables = ['dprri', 'dpdri', 'dprdprov', 'dprdkabko'];

// Inisialisasi variabel pencarian dan filter dengan validasi input
$searchKeyword = getParam($conn, 'search');
$filterPartai = getParam($conn, 'partai');
$filterInstansi = getParam($conn, 'instansi');
$filterDapil = getParam($conn, 'dapil');

// Flag untuk mengetahui jika sedang dalam mode pencarian atau filtering
$isSearchMode = !empty($searchKeyword);
$isFilterMode = !empty($filterPartai) || !empty($filterInstansi) || !empty($filterDapil);

// Menentukan jumlah data per halaman
$limit = 20;

// Menentukan halaman saat ini dengan validasi ketat
$page = getParam($conn, 'page', 1, true);
$offset = ($page - 1) * $limit;

// Filter tabel berdasarkan instansi yang dipilih
$activeTables = $tables;
if (!empty($filterInstansi) && in_array($filterInstansi, $tables)) {
    $activeTables = [$filterInstansi];
}

// Membangun SQL query untuk menggabungkan data dari semua tabel aktif
$unionQuery = buildUnionQuery($conn, $tables, $activeTables);

// Membangun WHERE conditions berdasarkan filter
$whereResult = buildWhereConditions($conn, $searchKeyword, $filterPartai, $filterDapil);
$whereConditions = $whereResult['conditions'];

// Mendapatkan total data untuk pagination
$totalData = countTotalData($conn, $unionQuery, $whereConditions);

// Menghitung jumlah halaman untuk pagination
$totalPages = ceil($totalData / $limit);

// Mendapatkan daftar dapil berdasarkan instansi yang dipilih
$dapilOptions = getDapilOptions($conn, $filterInstansi);

// Mendapatkan data partai dan logo untuk dropdown filter
$partyData = getPartyData($conn, $tables);

// Mengambil data legislatif untuk ditampilkan
$legislativeData = getLegislativeData(
    $conn,
    $unionQuery,
    $whereConditions,
    $limit,
    $offset
);

// ============================================================================
// RENDERING TAMPILAN
// ============================================================================
?>
<!DOCTYPE html>
<html lang="id">



    
        /* Efek loading langsung untuk tampilan cepat */
        body.form-submitting .content-wrapper {
            opacity: 0.6;
            pointer-events: none;
        }

        .content-wrapper {
            position: relative;
        }

        /* Gaya pesan error */
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
            border: 1px solid #f5c6cb;
            text-align: center;
        }

        /* Gaya untuk header tabel */
        .table-header {
            background-color: #f8f9fa;
            padding: 10px 15px;
            margin-top: 25px;
            border-radius: 5px 5px 0 0;
            font-weight: bold;
            border-bottom: 2px solid #e9ecef;
        }

        /* Kelas highlight untuk hasil pencarian - latar kuning */
        .highlight {
            background-color: #FFFF00;
            font-weight: bold;
            padding: 2px 2px;
            border-radius: 2px;
            color: #000;
        }

        /* Gaya untuk tooltip logo partai */
        .party-tooltip {
            display: none;
            position: absolute;
            background-color: #333;
            font-size: 15px;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            z-index: 100;
            font-weight: bold;
            white-space: nowrap;
            left: 50%;
            transform: translateX(-50%);
            top: -40px;
        }

        .party-tooltip:after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #333 transparent transparent transparent;
        }

        .party-logo-container {
            position: relative;
            display: inline-block;
        }

        .party-logo-container:hover .party-tooltip {
            display: block;
        }

        /* Tampilan informasi dapil yang lebih elegan */
        .dapil-info {
            display: flex;
            align-items: center;
            margin-top: 6px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            font-size: 12px;
            font-weight: 500;
            letter-spacing: 0.2px;
            color: #333;
            padding: 2px 4px 2px 4px;
        }

        .dapil-info:before {
            content: "\f3c5";
            /* Ikon penanda peta */
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            margin-right: 5px;
            color: #00897B;
            font-size: 12px;
        }

        /* Kontainer teks dapil untuk wrapping yang lebih baik */
        .dapil-text {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* Dapil info saat di-highlight */
        .dapil-info .highlight {
            background-color: #FFFF00;
            border-radius: 2px;
            padding: 2px 2px;
            font-weight: bold;
            color: #000;
            text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
        }

        /* Efek zoom untuk foto legislator */
        .zoom-effect {
            transition: transform 0.3s ease;
        }

        .zoom-effect:hover {
            transform: scale(1.1);
        }

        /* Mobile link styles - clean and compact */
        .mobile-link {
            display: none;
            /* Hidden by default */
            color: inherit;
            /* Inherit text color */
            text-decoration: none;
            /* Remove underline */
        }

        .mobile-name-link:hover {
            color: #00897B;
            /* Modern hover color */
        }

        .desktop-photo,
        .desktop-name {
            display: inline;
            /* Show by default */
        }

        <?php if ($isSearchMode || $isFilterMode): ?>.hide-on-search {
            display: none !important;
        }

        <?php endif; ?>

        /* Gaya Header Section */
        .header {
            /* Hapus background gradasi agar tidak menimpa warna asli gambar */
            background: none;
            color: white;
            padding: 3rem 1rem;
            text-align: center;
            border-radius: 0 0 20px 20px;
            margin-bottom: 1.5rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
            z-index: 1;
        }

        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: url("asset/legislatif.webp");
            background-size: cover;
            background-position: center;
            z-index: 0;
            /* Hapus opacity agar warna asli terlihat */
            /* Jika ingin efek gelap tanpa ubah warna asli, bisa pakai filter */
            filter: brightness(0.8);
            /* Atau sesuaikan misal 0.8 untuk sedikit gelap */
        }

        .header-content {
            max-width: 700px;
            margin: 0 auto;
            position: relative;
            z-index: 2;
        }

        .header-title {
            font-size: 35px;
            font-weight: bold;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 2px #000000;
        }

        .header-description {
            font-size: 16px;
            font-weight: bold;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 2px #000000;
        }

        /* Gaya Filter Section yang Ditingkatkan */
        .filter-section {
            margin: 18px 0 28px 0;
            background-color: #f8f9fa;
            padding: 22px;
            border-radius: 14px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 0, 0, 0.07);
            transition: all 0.25s ease;
        }

        .filter-container {
            max-width: 1120px;
            margin: 0 auto;
        }

        .filter-row {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .filter-item {
            display: flex;
            align-items: center;
            position: relative;
            flex: 1;
            min-width: 0;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
            border: 1px solid rgba(0, 0, 0, 0.09);
            padding: 0 14px;
            height: 46px;
            transition: all 0.2s ease;
        }

        .filter-item:hover {
            border-color: rgba(0, 0, 0, 0.18);
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.09);
            transform: translateY(-1px);
        }

        .search-filter-item {
            flex: 2;
        }

        /* Gaya filter item yang dinonaktifkan */
        .filter-item.disabled {
            opacity: 0.75;
            cursor: not-allowed;
            background-color: #f8f8f8;
            border-color: rgba(0, 0, 0, 0.05);
        }

        .filter-item.disabled select,
        .filter-item.disabled .filter-icon {
            pointer-events: none;
            color: #aaa;
            cursor: not-allowed;
        }

        .filter-item.disabled .dropdown-arrow {
            color: #ccc;
        }

        .filter-icon {
            color: #00897B;
            margin-right: 10px;
            font-size: 15px;
            opacity: 0.9;
        }

        .filter-item select {
            width: 100%;
            height: 100%;
            padding: 0 20px 0 0;
            border: none;
            background: transparent;
            appearance: none;
            font-family: 'Plus Jakarta Sans', sans-serif;
            font-size: 15px;
            font-weight: 500;
            color: #444;
            cursor: pointer;
            outline: none;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            max-height: 46px;
        }

        .filter-item select:focus {
            color: #000;
        }

        .dropdown-arrow {
            position: absolute;
            right: 12px;
            color: #aaa;
            font-size: 13px;
            pointer-events: none;
            transition: transform 0.2s ease;
        }

        .filter-item:hover .dropdown-arrow {
            color: #777;
        }

        .filter-item:focus-within .dropdown-arrow {
            transform: rotate(180deg);
            color: #00897B;
        }

        /* Gaya Pencarian yang Terintegrasi */
        .search-input-container {
            width: 100%;
            position: relative;
            display: flex;
            align-items: center;
        }

        #search-input {
            width: 100%;
            height: 46px;
            border-radius: 10px;
            border: none;
            background-color: transparent;
            padding: 0 50px 0 38px;
            font-size: 15px;
            color: #333;
            outline: none;
            font-weight: 400;
            letter-spacing: 0.2px;
        }

        #search-input::placeholder {
            color: #333;
            font-weight: 400;
            opacity: 0.75;
        }

        #search-input:focus {
            color: #000;
        }

        #search-input:focus::placeholder {
            color: #bbb;
        }

        .search-icon {
            position: absolute;
            left: 3px;
            color: #00897B;
            font-size: 15px;
            opacity: 0.9;
            pointer-events: none;
            transition: all 0.2s ease;
        }

        .filter-item:hover .search-icon,
        .filter-item:focus-within .search-icon {
            opacity: 1;
            transform: scale(1.05);
        }

        .search-button {
            position: absolute;
            right: 3px;
            width: 28px;
            height: 28px;
            border-radius: 15px;
            background-color: #00897B;
            border: none;
            color: white;
            font-size: 13px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.25s ease;
            opacity: 0.9;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .search-button:hover {
            opacity: 1;
            background-color: #007b6b;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
        }

        .search-button:active {
            transform: translateY(0);
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        /* Gaya dropdown kustom untuk daftar besar */
        select.scrollable-select {
            scrollbar-width: thin;
        }

        /* Gaya tambahan untuk scroll dropdown */
        select.scrollable-select::-webkit-scrollbar {
            width: 6px;
        }

        select.scrollable-select::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 6px;
        }

        select.scrollable-select::-webkit-scrollbar-thumb {
            background: #ddd;
            border-radius: 6px;
        }

        select.scrollable-select::-webkit-scrollbar-thumb:hover {
            background: #ccc;
        }

        /* Gaya Select2 yang sesuai dengan desain kita */
        .select2-container {
            width: 100% !important;
            height: 46px !important;
        }

        /* Perbaikan masalah lebar dropdown */
        .select2-dropdown {
            width: auto !important;
            min-width: 200px !important;
            max-width: 250px !important;
            left: 0 !important;
        }

        .select2-results__option {
            width: auto !important;
            display: block !important;
        }

        .select2-results__option--highlighted {
            width: auto !important;
            display: block !important;
        }

        .select2-container--default .select2-results>.select2-results__options {
            width: auto !important;
        }

        .select2-container--default .select2-selection--single {
            height: 46px !important;
            display: flex !important;
            align-items: center !important;
            background-color: transparent !important;
            border: none !important;
            outline: none !important;
            box-shadow: none !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #444 !important;
            font-family: 'Plus Jakarta Sans', sans-serif !important;
            font-size: 15px !important;
            font-weight: 500 !important;
            padding-left: 0 !important;
            line-height: 46px !important;
            padding-right: 32px !important;
            text-overflow: ellipsis !important;
            overflow: hidden !important;
            white-space: nowrap !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px !important;
            position: absolute !important;
            right: 1px !important;
        }

        /* Perbaikan posisi tombol tutup (X) */
        .select2-container--default .select2-selection--single .select2-selection__clear {
            position: absolute !important;
            right: 25px !important;
            z-index: 10 !important;
            margin-right: 0 !important;
            color: white !important;
            font-size: 13px !important;
            font-weight: 700 !important;
            line-height: 20px !important;
            width: 20px !important;
            height: 20px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            border-radius: 50% !important;
            background-color: #f44336 !important;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) !important;
            transition: all 0.2s ease !important;
            border: none !important;
            opacity: 0.9 !important;
            margin-top: 0 !important;
            transform: translateY(0) !important;
            padding: 0 !important;
            font-family: Arial, sans-serif !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__clear:hover {
            background-color: #d32f2f !important;
            /* Warna merah yang lebih gelap saat hover */
            transform: scale(1.1) !important;
            opacity: 1 !important;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
        }

        .select2-dropdown {
            border-radius: 8px !important;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
            border: 1px solid rgba(0, 0, 0, 0.1) !important;
            overflow: hidden !important;
        }

        .select2-search--dropdown {
            padding: 8px !important;
            background-color: #f8f9fa !important;
            border-bottom: 1px solid #eee !important;
        }

        .select2-search--dropdown .select2-search__field {
            border-radius: 4px !important;
            padding: 8px 10px !important;
            border: 1px solid #ddd !important;
            font-family: 'Plus Jakarta Sans', sans-serif !important;
            font-size: 14px !important;
        }

        /* Placeholder untuk kotak pencarian */
        .select2-search--dropdown .select2-search__field::placeholder {
            color: #676767 !important;
            opacity: 0.8 !important;
            font-size: 14px !important;
            font-family: 'Plus Jakarta Sans', sans-serif !important;
        }

        .select2-results__option {
            padding: 8px 12px !important;
            font-family: 'Plus Jakarta Sans', sans-serif !important;
            font-size: 15px !important;
            font-weight: 600;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #f44336 !important;
            color: white !important;
        }

        /* Pastikan teks nama partai berwarna putih saat opsi di-highlight */
        .select2-container--default .select2-results__option--highlighted[aria-selected] .party-name {
            color: white !important;
        }

        /* Perbaikan untuk select2 yang dinonaktifkan */
        .filter-item.disabled .select2-container {
            pointer-events: none;
        }

        .filter-item.disabled .select2-selection {
            opacity: 0.7;
            background-color: #f8f8f8 !important;
        }

        /* Logo partai dalam dropdown */
        .party-option {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .party-logo-dropdown {
            width: 20px;
            height: 20px;
            object-fit: contain;
        }

        .selected-party {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .party-logo-selected {
            width: 16px;
            height: 16px;
            object-fit: contain;
        }

        /* Gaya Jumlah Hasil */
        .results-count {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }

        /* Gaya pencarian terintegrasi dengan filter */
        .search-summary {
            font-size: 16px;
        }

        .search-summary .count {
            font-weight: bold;
            color: #f44336;
        }

        .search-summary .keyword {
            font-weight: bold;
        }

        /* Gaya Jumlah Hasil untuk filter */
        .filter-results {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 1px 5px #00897b;
            margin-bottom: 2rem;
        }

        /* Tombol Kembali untuk hasil pencarian */
        .show-all {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            background-color: #00897B;
            color: white;
            border-radius: 20px;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .show-all:hover {
            background-color: #00695C;
            transform: translateY(-2px);
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        .show-all i {
            font-size: 13px;
        }

        /* Tombol Reset untuk hasil filter */
        .reset-button {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            background-color: #f44336;
            color: white;
            border-radius: 13px;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .reset-button:hover {
            background-color: #d32f2f;
            transform: translateY(-2px);
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        .reset-button i {
            font-size: 13px;
        }

        /* Gaya responsif untuk desktop dan mobile */
        @media screen and (max-width: 768px) {

            /* Hide desktop elements */
            .desktop-profile-btn,
            .desktop-photo,
            .desktop-name {
                display: none !important;
            }

            /* Show mobile elements */
            .mobile-link {
                display: block;
            }

            /* Make profile button cell take minimal space */
            .profile-btn-cell {
                display: none !important;
            }

            /* Style for photo link */
            .mobile-photo-link img {
                border: 1px solid #eee;
                transition: all 0.2s ease;
            }

            .mobile-photo-link:active img {
                border-color: #00897B;
            }

            .table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .table-container table {
                width: 100%;
                table-layout: fixed;
                border-spacing: 0;
                border-collapse: separate;
            }

            /* Terapkan lebar kolom untuk mobile */
            .table-container table tr th:nth-child(1),
            .table-container table tr td:nth-child(1) {
                width: 15%;
                padding: 8px 4px 8px 5px;
            }

            .table-container table tr th:nth-child(2),
            .table-container table tr td:nth-child(2) {
                width: 45%;
                /* Increase width for name column */
                padding: 8px 15px 8px 5px;
                text-align: left;
            }

            /* Tampilkan dan gaya kolom instansi untuk mobile */
            .instansi-column {
                display: table-cell !important;
                width: 40%;
                /* Adjusted for better use of space */
                padding: 8px 5px !important;
                text-align: left;
            }

            /* Buat label instansi lebih kompak pada mobile */
            .instansi-column span {
                padding: 2px 4px !important;
                font-size: 11px !important;
                white-space: normal !important;
                word-break: break-word !important;
                display: inline-block;
                max-width: 100%;
            }

            /* Gaya dapil yang lebih baik untuk mobile */
            .dapil-info {
                margin-top: 6px;
                font-size: 10px;
                padding: 2px 4px 2px 4px;
                width: 100%;
                box-sizing: border-box;
                line-height: 1.3;
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                word-break: break-word;
                background-color: rgba(0, 137, 123, 0.08);
                border-radius: 4px;
            }

            .dapil-info:before {
                font-size: 9px;
                display: inline-block;
                min-width: 12px;
                margin-right: -5px;
            }

            /* Penanganan highlight yang lebih baik di mobile */
            .dapil-info .highlight {
                padding: 1px 2px;
                font-weight: 600;
                display: inline;
                line-height: 1.4;
                white-space: normal;
                word-break: break-word;
            }

            /* Sembunyikan kolom logo partai di mobile */
            .table-container table tr th:nth-child(4),
            .table-container table tr td:nth-child(4) {
                display: none;
            }

            .table-container table tr th:nth-child(5),
            .table-container table tr td:nth-child(5) {
                width: 0;
                /* Minimize width */
                padding: 0;
            }

            /* Buat logo partai lebih terlihat di mobile */
            .party-logo-container {
                display: flex;
                justify-content: center;
            }

            .party-logo-container img {
                width: 35px;
                height: 35px;
            }

            /* Sembunyikan tombol profil di mobile */
            .mobile-profile-btn {
                display: none;
            }

            .desktop-profile-btn {
                display: none;
            }

            /* Sesuaikan ukuran foto untuk mobile */
            .legislator-photo {
                width: 45px;
                height: 60px;
                display: block;
                margin: 0 auto;
            }

            /* Ukuran font yang lebih baik untuk mobile */
            .table-container table th,
            .table-container table td {
                font-size: 14px;
                vertical-align: middle;
            }

            /* Kontainer pagination yang lebih baik */
            .pagination-container {
                margin: 35px 0;
                display: flex;
                justify-content: center;
                width: 100%;
            }

            /* Tata letak pagination yang lebih baik untuk mobile */
            .pagination {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
                align-items: center;
                gap: 2px;
                padding: 8px 8px;
                font-size: 14px;
                max-width: 100%;
            }

            /* Sembunyikan nomor pagination ekstra di mobile - hanya tampilkan 3 halaman */
            .pagination a.page-number {
                display: none;
            }

            /* Tampilkan hanya halaman saat ini dan satu halaman sebelum/sesudah */
            .pagination a.page-number.active,
            .pagination a.page-number.active-adjacent {
                display: inline-flex;
            }

            /* Buat teks dan nomor halaman dengan jarak yang baik */
            .pagination>* {
                margin: 2px;
            }

            /* Gaya tombol pagination untuk tap yang lebih mudah */
            .pagination a {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                min-width: 32px;
                height: 32px;
                padding: 0 8px;
                border-radius: 4px;
                background-color: #ffffff;
                text-decoration: none;
                color: #333;
                border: 1px solid #ddd;
                font-weight: bold;
                font-size: 14px;
            }

            /* Gaya halaman aktif */
            .pagination a.active {
                background-color: #00897B;
                color: white;
                border-color: #00897B;
            }

            /* Gaya ikon next/prev */
            .pagination a i {
                font-size: 13px;
            }

            /* Gaya responsif untuk bagian hero pencarian */
            .header-title {
                font-size: 24px;
            }

            .header-description {
                font-size: 14px;
            }

            /* Gaya responsif filter */
            .filter-section {
                padding: 16px 14px;
                margin: 12px 0 22px 0;
                border-radius: 12px;
            }

            .filter-row {
                flex-direction: column;
                align-items: stretch;
                gap: 12px;
            }

            .filter-item {
                width: 100%;
                height: 44px;
                padding: 0 12px;
                border-radius: 8px;
            }

            .filter-item select {
                font-size: 15px;
            }

            .filter-icon {
                font-size: 15px;
                margin-right: 8px;
            }

            .dropdown-arrow {
                right: 10px;
                font-size: 12px;
            }

            /* Penyesuaian pencarian mobile */
            #search-input {
                height: 44px;
                padding: 0 45px 0 36px;
                font-size: 15px;
            }

            .search-icon {
                left: 12px;
                font-size: 15px;
            }

            .search-button {
                height: 30px;
                width: 30px;
                right: 7px;
                font-size: 12px;
            }

            /* Tombol "Kembali" responsif */
            .show-all {
                width: auto;
                min-width: 100px;
                max-width: 150px;
                justify-content: center;
                padding: 8px 12px;
                border-radius: 6px;
                font-size: 13px;
                margin-left: auto;
                margin-right: 0;
            }

            .show-all i {
                font-size: 12px;
            }

            /* Tombol reset responsif - PERBAIKAN */
            .reset-button {
                width: auto;
                min-width: 100px;
                max-width: 150px;
                justify-content: center;
                padding: 8px 12px;
                border-radius: 6px;
                font-size: 13px;
                margin-left: auto;
                margin-right: 0;
            }

            .reset-button i {
                font-size: 12px;
            }

            /* Perbaikan kontainer results-count untuk tampilan mobile yang lebih baik */
            .results-count {
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: wrap;
                gap: 10px;
                padding: 10px 12px;
                margin-bottom: 15px;
            }

            .search-summary {
                font-size: 14px;
                flex: 1;
                min-width: 200px;
            }

            /* Gaya responsif Select2 */
            .select2-container {
                height: 44px !important;
            }

            .select2-container--default .select2-selection--single {
                height: 44px !important;
            }

            .select2-container--default .select2-selection--single .select2-selection__rendered {
                font-size: 15px !important;
                line-height: 44px !important;
            }

            .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 44px !important;
            }

            /* Penyesuaian tombol hapus responsif */
            .select2-container--default .select2-selection--single .select2-selection__clear {
                width: 16px !important;
                height: 16px !important;
                font-size: 10px !important;
                margin-right: 6px !important;
            }

            .select2-results__option {
                padding: 6px 8px !important;
                font-size: 13px !important;
            }

            /* Pastikan dropdown pas di mobile */
            .select2-container .select2-dropdown {
                max-width: 92vw !important;
                font-size: 13px !important;
            }

            /* Gaya responsif logo partai */
            .party-logo-dropdown {
                width: 16px;
                height: 16px;
            }

            .party-logo-selected {
                width: 14px;
                height: 14px;
            }
        }

        /* Gaya khusus untuk layar sangat kecil */
        @media screen and (max-width: 320px) {

            /* Penyesuaian untuk layar sangat kecil */
            .table-container {
                font-size: 12px;
            }

            .legislator-photo {
                width: 35px;
                height: 45px;
            }

            .table-container table tr th:nth-child(1),
            .table-container table tr td:nth-child(1) {
                width: 12%;
            }

            .instansi-column span {
                font-size: 10px !important;
            }

            .dapil-info {
                font-size: 9px;
            }

            /* Padding lebih kecil untuk tombol */
            .mobile-profile-btn {
                padding: 6px 8px;
                font-size: 12px;
            }

            /* Sesuaikan input pencarian */
            #search-input {
                height: 42px;
                font-size: 15px;
                padding: 0 42px 0 34px;
            }

            .search-button {
                width: 28px;
                height: 28px;
                right: 7px;
            }

            /* Buat pagination lebih kompak */
            .pagination a {
                min-width: 28px;
                height: 28px;
                font-size: 12px;
            }

            /* Penyesuaian bagian filter */
            .filter-section {
                padding: 14px 12px;
            }

            .filter-item {
                height: 42px;
            }

            .filter-item select {
                font-size: 15px;
            }

            .filter-icon {
                font-size: 15px;
                margin-right: 5px;
            }

            /* Penyesuaian Select2 untuk layar sangat kecil */
            .select2-container {
                height: 42px !important;
            }

            .select2-container--default .select2-selection--single {
                height: 42px !important;
            }

            .select2-container--default .select2-selection--single .select2-selection__rendered {
                font-size: 15px !important;
                line-height: 42px !important;
            }

            .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 42px !important;
            }

            /* Tombol hapus lebih kecil lagi */
            .select2-container--default .select2-selection--single .select2-selection__clear {
                width: 15px !important;
                height: 15px !important;
                margin-right: 5px !important;
            }

            /* Tombol "Kembali" lebih kompak untuk layar kecil */
            .show-all {
                min-width: 90px;
                padding: 6px 10px;
                font-size: 12px;
            }

            .show-all i {
                font-size: 11px;
            }

            /* Tombol reset lebih kompak untuk layar kecil */
            .reset-button {
                min-width: 90px;
                padding: 6px 10px;
                font-size: 12px;
            }

            .reset-button i {
                font-size: 11px;
            }

            /* Tampilan hasil lebih kompak */
            .results-count {
                padding: 8px 10px;
            }

            .search-summary {
                font-size: 13px;
            }

            .active-filters {
                font-size: 11px;
                padding: 1px 4px;
            }
        }

        /* Gaya desktop */
        @media screen and (min-width: 769px) {
            .mobile-link {
                display: none;
            }

            .desktop-photo,
            .desktop-name {
                display: inline;
            }

            .mobile-profile-btn {
                display: none;
            }

            .desktop-profile-btn {
                display: inline-block;
            }

            /* Tampilan dapil yang lebih baik di desktop */
            .dapil-info {
                width: 95%;
                margin-top: 7px;
                font-size: 12px;
            }
        }

        /* Animasi shake untuk input pencarian */
        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            10%,
            30%,
            50%,
            70%,
            90% {
                transform: translateX(-5px);
            }

            20%,
            40%,
            60%,
            80% {
                transform: translateX(5px);
            }
        }
    

<body>
    <div class="container">
        <?php include 'menu.php'; // Include menu file 
        ?>

        <div class="content-wrapper" id="mainContent">
            <!-- Header Section -->
            <div class="header <?php echo ($isSearchMode || $isFilterMode) ? 'hide-on-search' : ''; ?>">
                <div class="header-content">
                    <h1 class="header-title">LEGISLATIF</h1>
                    <h1 class="header-description">Pejabat legislatif dari seluruh Indonesia periode 2024-2029</h1>
                </div>
            </div>

            <!-- Filter Section - sembunyikan saat pencarian -->
            <div class="filter-section <?php echo $isSearchMode ? 'hide-on-search' : ''; ?>">
                <div class="filter-container">
                    <form method="GET" action="" id="filterForm">
                        <div class="filter-row">
                            <!-- Form pencarian (paling kiri) -->
                            <div class="filter-item search-filter-item">
                                <div class="search-input-container">
                                    <span class="search-icon"><i class="fas fa-search"></i></span>
                                    <input type="text" id="search-input" name="search"
                                        placeholder="Cari nama disini..."
                                        value="<?php echo htmlspecialchars($searchKeyword); ?>">
                                    <button type="submit" class="search-button">
                                        <i class="fa-solid fa-arrow-right"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Instansi (di sebelah kanan form pencarian) -->
                            <div class="filter-item" id="instansi-filter-container">
                                <div class="filter-icon">
                                    <i class="fas fa-building"></i>
                                </div>
                                <select name="instansi" id="instansi-filter">
                                    <option value="">INSTANSI</option>
                                    <option value="dprri" <?php echo $filterInstansi == 'dprri' ? 'selected' : ''; ?>>🟡 DPR - RI</option>
                                    <option value="dpdri" <?php echo $filterInstansi == 'dpdri' ? 'selected' : ''; ?>>🔴 DPD - RI</option>
                                    <option value="dprdprov" <?php echo $filterInstansi == 'dprdprov' ? 'selected' : ''; ?>>🔵 DPRD Provinsi</option>
                                    <option value="dprdkabko" <?php echo $filterInstansi == 'dprdkabko' ? 'selected' : ''; ?>>🟢 DPRD Kabupaten / Kota</option>
                                </select>
                                <div class="dropdown-arrow">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>

                            <!-- Dapil (di sebelah kanan Instansi, disabled saat instansi belum dipilih) -->
                            <div class="filter-item <?php echo empty($filterInstansi) ? 'disabled' : ''; ?>" id="dapil-filter-container">
                                <div class="filter-icon">
                                    <i class="fas fa-map-marker-alt"></i>
                                </div>
                                <select name="dapil" id="dapil-filter" <?php echo empty($filterInstansi) ? 'disabled' : ''; ?>>
                                    <option value="">DAPIL</option>
                                    <?php foreach ($dapilOptions as $dapil): ?>
                                        <option value="<?php echo htmlspecialchars($dapil); ?>"
                                            <?php echo $filterDapil == $dapil ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($dapil); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="dropdown-arrow">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>

                            <!-- Partai (di sebelah kanan Dapil) -->
                            <div class="filter-item <?php echo (empty($filterInstansi) || $filterInstansi == 'dpdri') ? 'disabled' : ''; ?>" id="partai-filter-container">
                                <div class="filter-icon">
                                    <i class="fas fa-flag"></i>
                                </div>
                                <select name="partai" id="partai-filter" <?php echo (empty($filterInstansi) || $filterInstansi == 'dpdri') ? 'disabled' : ''; ?>>
                                    <?php echo renderPartyDropdown($partyData, $filterPartai); ?>
                                </select>
                                <div class="dropdown-arrow">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Results Count Display for Search -->
            <?php if ($isSearchMode && $totalData > 0): ?>
                <br>
                <div class="results-count">
                    <div class="search-summary">
                        🔍 ditemukan <span class="count"><?php echo $totalData; ?></span> hasil
                        <span class="keyword"><?php echo htmlspecialchars($searchKeyword); ?></span>
                    </div>
                    <a href="legislatif.php" class="show-all">
                        <i class="fa-solid fa-arrow-left"></i> Kembali
                    </a>
                </div>
            <?php endif; ?>

            <!-- Results Count Display for Filter -->
            <?php if ($isFilterMode && !$isSearchMode && $totalData > 0): ?>
                <div class="results-count filter-results">
                    <div class="search-summary">
                        🔍 ditemukan <span class="count"><?php echo $totalData; ?></span> hasil filter
                    </div>
                    <a href="legislatif.php" class="reset-button">
                        <i class="fas fa-undo-alt"></i> Reset
                    </a>
                </div>
            <?php endif; ?>

            <?php
            /**
             * Menampilkan hasil pencarian atau pesan tidak ada hasil
             */
            try {
                if ($legislativeData && count($legislativeData) > 0) {
                    // Tampilkan hasil dalam tabel
                    echo renderLegislativeTable($legislativeData, $conn, $searchKeyword);

                    // Tampilkan pagination
                    echo renderPagination($page, $totalPages, $searchKeyword, $filterPartai, $filterInstansi, $filterDapil);
                } else {
                    // Tampilkan pesan jika tidak ada hasil
                    echo renderNoResults($searchKeyword, $isSearchMode, $isFilterMode);
                }
            } catch (Exception $e) {
                // Tampilkan pesan error yang user-friendly
                renderErrorPage("⚠️ Database belum diupdate, silahkan coba lagi nanti");
                logError("Error saat menjalankan query: " . $e->getMessage());
            }
            ?>

            <?php include 'footer.php'; // Include footer 
            ?>
        </div>
    </div>

    <script>
        /**
         * Script untuk mengatur fungsi filter dan pencarian
         * Dijalankan setelah DOM content loaded
         */
        document.addEventListener('DOMContentLoaded', function() {
            // Inisialisasi Select2 jika tersedia
            if (typeof $.fn.select2 !== 'undefined') {
                /**
                 * Format dropdown options untuk menampilkan logo partai
                 * @param {Object} party - Opsi partai yang akan diformat
                 * @return {jQuery|string} - Element yang sudah diformat
                 */
                function formatParty(party) {
                    if (!party.id) {
                        return party.text;
                    }

                    const $option = $(party.element);
                    const logoUrl = $option.data('logo');

                    if (!logoUrl) {
                        return party.text;
                    }

                    const $party = $(
                        `<div class="party-option">
                            <img src="${logoUrl}" class="party-logo-dropdown" />
                            <span class="party-name">${party.text}</span>
                        </div>`
                    );

                    return $party;
                }

                /**
                 * Format selected option untuk menampilkan logo partai
                 * @param {Object} party - Opsi partai yang akan diformat
                 * @return {jQuery|string} - Element yang sudah diformat
                 */
                function formatPartySelection(party) {
                    if (!party.id) {
                        return party.text;
                    }

                    const $option = $(party.element);
                    const logoUrl = $option.data('logo');

                    if (!logoUrl) {
                        return party.text;
                    }

                    return $(
                        `<div class="selected-party">
                            <img src="${logoUrl}" class="party-logo-selected" />
                            <span>${party.text}</span>
                        </div>`
                    );
                }

                // Inisialisasi select2 untuk filter dapil dengan pencarian
                $('#dapil-filter').select2({
                    placeholder: "DAPIL",
                    allowClear: true,
                    width: '100%',
                    minimumResultsForSearch: 8 // Tampilkan search box jika minimal ada 8 opsi
                });

                // Inisialisasi select2 untuk filter partai dengan custom template
                $('#partai-filter').select2({
                    placeholder: "PARTAI",
                    allowClear: true,
                    width: '100%',
                    minimumResultsForSearch: 8,
                    templateResult: formatParty,
                    templateSelection: formatPartySelection
                });

                // Inisialisasi select2 untuk filter instansi
                $('#instansi-filter').select2({
                    placeholder: "INSTANSI",
                    allowClear: true,
                    width: '100%',
                    minimumResultsForSearch: -1 // Nonaktifkan pencarian untuk instansi karena jumlah opsi sedikit
                });

                // Tambahkan placeholder untuk search box di Select2
                $('#dapil-filter').on('select2:open', function() {
                    $('.select2-search__field[aria-controls="select2-dapil-filter-results"]').attr('placeholder', 'Cari dapil...');
                });

                $('#partai-filter').on('select2:open', function() {
                    $('.select2-search__field[aria-controls="select2-partai-filter-results"]').attr('placeholder', 'Cari partai...');
                });

                // Langsung paksa ukuran dropdown
                function fixSelect2Dropdowns() {
                    $('.select2-results__options').css('width', '200px');
                    $('.select2-results__option').css('width', '200px');
                    $('.select2-dropdown').css('width', '200px');
                }

                $('select').on('select2:open', function() {
                    setTimeout(fixSelect2Dropdowns, 0);
                });

                /**
                 * Perbarui status filter berdasarkan pilihan instansi
                 * Aktifkan/nonaktifkan filter dapil dan partai sesuai instansi yang dipilih
                 */
                function updateSelectState() {
                    // Atur status filter dapil
                    if ($('#instansi-filter').val()) {
                        $('#dapil-filter-container').removeClass('disabled');
                        $('#dapil-filter').prop('disabled', false).trigger('change');
                    } else {
                        $('#dapil-filter-container').addClass('disabled');
                        $('#dapil-filter').prop('disabled', true).val('').trigger('change');
                    }

                    // Atur status filter partai
                    if ($('#instansi-filter').val() === 'dpdri' || $('#instansi-filter').val() === '') {
                        $('#partai-filter-container').addClass('disabled');
                        $('#partai-filter').prop('disabled', true).val('').trigger('change');
                    } else {
                        $('#partai-filter-container').removeClass('disabled');
                        $('#partai-filter').prop('disabled', false).trigger('change');
                    }
                }

                // Atur status awal
                updateSelectState();

                // Perbarui saat instansi berubah dan kirim formulir
                $('#instansi-filter').on('change', function() {
                    updateSelectState();
                    // Kirim formulir setelah penundaan untuk menghindari pengiriman berulang
                    setTimeout(function() {
                        document.getElementById('filterForm').submit();
                    }, 100);
                });

                // Kirim formulir otomatis saat filter berubah
                $('#dapil-filter, #partai-filter').on('change', function() {
                    document.getElementById('filterForm').submit();
                });

                // Sembunyikan tanda panah dropdown untuk select2
                $('.filter-item').each(function() {
                    if ($(this).find('.select2').length > 0) {
                        $(this).find('.dropdown-arrow').hide();
                    }
                });

            } else {
                // Fallback jika Select2 tidak tersedia
                $('#dapil-filter, #partai-filter').addClass('scrollable-select');

                // Kirim formulir otomatis saat select berubah
                const filterSelects = document.querySelectorAll('#filterForm select');
                filterSelects.forEach(select => {
                    select.addEventListener('change', function() {
                        document.getElementById('filterForm').submit();
                    });
                });

                // Tangani status filter
                const instansiFilter = document.getElementById('instansi-filter');
                const dapilFilterContainer = document.getElementById('dapil-filter-container');
                const partaiFilterContainer = document.getElementById('partai-filter-container');

                /**
                 * Tangani visibilitas filter dapil
                 * Aktifkan/nonaktifkan berdasarkan pilihan instansi
                 */
                function handleDapilFilterVisibility() {
                    if (instansiFilter.value) {
                        dapilFilterContainer.classList.remove('disabled');
                        document.getElementById('dapil-filter').disabled = false;
                    } else {
                        dapilFilterContainer.classList.add('disabled');
                        document.getElementById('dapil-filter').disabled = true;
                        document.getElementById('dapil-filter').value = '';
                    }
                }

                /**
                 * Tangani visibilitas filter partai
                 * Aktifkan/nonaktifkan berdasarkan pilihan instansi
                 */
                function handlePartaiFilterVisibility() {
                    if (instansiFilter.value === 'dpdri' || instansiFilter.value === '') {
                        partaiFilterContainer.classList.add('disabled');
                        document.getElementById('partai-filter').disabled = true;
                        document.getElementById('partai-filter').value = '';
                    } else {
                        partaiFilterContainer.classList.remove('disabled');
                        document.getElementById('partai-filter').disabled = false;
                    }
                }

                // Atur status awal dan tambahkan event listener
                handleDapilFilterVisibility();
                handlePartaiFilterVisibility();

                instansiFilter.addEventListener('change', function() {
                    handleDapilFilterVisibility();
                    handlePartaiFilterVisibility();
                });
            }

            /**
             * Pastikan gambar dimuat dengan penanganan error
             * Gunakan gambar cadangan jika gambar asli gagal dimuat
             */
            const images = document.querySelectorAll('.legislator-photo');

            images.forEach(img => {
                img.onerror = function() {
                    this.src = 'images/default-profile.png'; // Gambar cadangan
                    this.onerror = null; // Cegah loop tak terbatas
                };
            });

            /**
             * Tambahkan indikator loading untuk pencarian
             * dan validasi input search
             */
            const filterForm = document.getElementById('filterForm');
            const searchInput = document.getElementById('search-input');

            if (filterForm && searchInput) {
                // Indikator loading saat formulir dikirim
                filterForm.addEventListener('submit', function(e) {
                    // Periksa apakah input pencarian kosong
                    if (searchInput.value.trim() === '' && document.activeElement === document.querySelector('.search-button')) {
                        e.preventDefault(); // Cegah pengiriman formulir

                        // Tampilkan efek shake dan highlight input sebagai error
                        searchInput.classList.add('error');
                        searchInput.style.borderColor = '#ff5252';
                        searchInput.style.animation = 'shake 0.5s';

                        // Hapus styling error setelah animasi selesai
                        setTimeout(() => {
                            searchInput.classList.remove('error');
                            searchInput.style.borderColor = '';
                            searchInput.style.animation = '';
                        }, 800);
                    } else {
                        // Jika input tidak kosong, tampilkan status loading
                        document.body.classList.add('form-submitting');
                    }
                });
            }
        });
    </script>
</body>

</html>

<?php
// Tutup koneksi database
$conn->close();
?>