<?php
// ==================== PROSES QUERY DATA ====================
// Query untuk mengambil data anggota dengan join ke user
$query = mysql_query("
    SELECT 
        a.*,
        u.username,
        u.nama as nama_lengkap,
        u.institusi,
        u.telpon as telepon_user,
        u.email,
        u.status as status_user
    FROM anggota a
    LEFT JOIN user u ON a.id_user = u.id
    WHERE u.idweb = '$idweb' AND u.role = 'member' AND aktif = 'Y'
    ORDER BY a.tgl_expired DESC, a.aktif DESC
");

$all_members = [];
while ($row = mysql_fetch_assoc($query)) {
    $all_members[] = $row;
}

$total_data = count($all_members);

// Hitung statistik
$aktif_count = 0;
$expired_count = 0;
$today = date('Y-m-d');
foreach ($all_members as $member) {
    if ($member['aktif'] == 'Y') {
        $aktif_count++;
        // Cek apakah sudah expired
        if (strtotime($member['tgl_expired']) < strtotime($today)) {
            $expired_count++;
        }
    }
}
?>
<!-- ==================== CSS DATATABLES ==================== -->
<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css" rel="stylesheet">

<style>
    .membership-card {
        transition: all 0.3s ease;
        border: 1px solid var(--gray-200);
    }
    
    .membership-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .status-badge {
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.65rem;
        font-weight: 500;
    }
    
    .badge-active {
        background-color: #d1fae5;
        color: #065f46;
        border: 1px solid #a7f3d0;
    }
    
    .badge-inactive {
        background-color: #fee2e2;
        color: #991b1b;
        border: 1px solid #fecaca;
    }
    
    .badge-expired {
        background-color: #fef3c7;
        color: #92400e;
        border: 1px solid #fde68a;
    }
    
    .badge-expiring {
        background-color: #fef3c7;
        color: #92400e;
        border: 1px solid #fde68a;
    }
    
    .badge-perpanjangan {
        background-color: #dbeafe;
        color: #1e40af;
        border: 1px solid #bfdbfe;
    }
    
    .table-membership {
        font-size: 0.95rem;
    }
    
    .table-membership th {
        background-color: #f8fafc;
        font-weight: 600;
        color: #334155;
        border-bottom: 2px solid #e2e8f0;
    }
    
    .table-membership td {
        vertical-align: middle;
        color: #475569;
    }
    
    .action-buttons-vertical {
        display: flex;
        flex-direction: column;
        gap: 4px;
        align-items: center;
    }
    
    .action-buttons-vertical .btn {
        width: 100%;
        max-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
        padding: 4px 8px;
        font-size: 0.85rem;
    }
    
    .pagination-custom .page-item.active .page-link {
        background-color: #4361ee;
        border-color: #4361ee;
        color:white;
    }
    
    .pagination-custom .page-link {
        color: #4361ee;
        border: 1px solid #e2e8f0;
        margin: 0 3px;
        border-radius: 6px;
        padding: 6px 12px;
    }
    
    .pagination-custom .page-link:hover {
        background-color: #f1f5f9;
    }
    
    .filter-card {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.25rem;
        margin-bottom: 1.5rem;
    }
    
    .membership-info {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }
    
    .membership-no {
        font-weight: 500;
        color: #1e293b;
    }
    
    .membership-name {
        color: #64748b;
        font-size: 0.85rem;
    }
    
    /* Mobile Responsive */
    @media (max-width: 768px) {
        .table-responsive {
            border: 0;
        }
        
        .table-membership thead {
            display: none;
        }
        
        .table-membership tbody tr {
            display: block;
            margin-bottom: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 8px;
        }
        
        .table-membership tbody td {
            display: block;
            text-align: left !important;
            border: none;
            padding: 0.75rem;
            position: relative;
            padding-left: 45%;
        }
        
        .table-membership tbody td:before {
            content: attr(data-label);
            position: absolute;
            left: 1rem;
            width: 40%;
            font-weight: 600;
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .table-membership tbody td:first-child {
            padding-top: 1rem;
            background-color: rgba(0,0,0,0.02);
            border-bottom: 1px solid #dee2e6;
        }
        
        .table-membership tbody td:last-child {
            padding-bottom: 1rem;
        }
        
        .action-buttons-vertical {
            align-items: flex-start;
        }
        
        .action-buttons-vertical .btn {
            max-width: 100%;
        }
    }
    
    .membership-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: linear-gradient(135deg, #4361ee 0%, #3a56d4 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 1rem;
        text-transform: uppercase;
    }
    
    .date-info {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }
    
    .date-main {
        font-weight: 500;
        color: #1e293b;
    }
    
    .date-days {
        color: #64748b;
        font-size: 0.85rem;
    }
    
    .location-info {
        display: flex;
        flex-direction: column;
        gap: 2px;
    }
    
    .location-main {
        font-weight: 500;
        color: #1e293b;
    }
    
    .location-detail {
        color: #64748b;
        font-size: 0.85rem;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Manajemen Keanggotaan</h4>
        <p class="text-muted mb-0">Kelola data keanggotaan PAPENTARA</p>
    </div>
    <div>
        <a href="users-manage/" class="btn btn-primary">
            <i data-lucide="users" width="16"></i>
            Kelola Pengguna
        </a>
    </div>
</div>

<!-- ==================== NOTIFIKASI ==================== -->
<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <i data-lucide="check-circle" class="me-2"></i>
    <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <i data-lucide="alert-circle" class="me-2"></i>
    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- ==================== FILTER REAL-TIME ==================== -->
<div class="filter-card">
    <h6 class="fw-bold mb-3">Filter Keanggotaan</h6>
    <div class="row g-3">
        <div class="col-md-3">
            <label class="form-label fw-medium">Status</label>
            <select class="form-select" id="filterStatus">
                <option value="">Semua Status</option>
                <option value="aktif">Aktif</option>
                <option value="nonaktif">Non-Aktif</option>
                <option value="expired">Kadaluarsa</option>
                <option value="expiring">Akan Kadaluarsa</option>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label fw-medium">Provinsi</label>
            <select class="form-select" id="filterProvinsi">
                <option value="">Semua Provinsi</option>
                <?php
                $provinsi_query = mysql_query("SELECT DISTINCT provinsi FROM anggota WHERE provinsi != '' ORDER BY provinsi");
                while ($prov = mysql_fetch_assoc($provinsi_query)):
                ?>
                <option value="<?php echo htmlspecialchars($prov['provinsi']); ?>">
                    <?php echo htmlspecialchars($prov['provinsi']); ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label fw-medium">Kab/Kota</label>
            <select class="form-select" id="filterKabkota">
                <option value="">Semua Kab/Kota</option>
                <?php
                $kabkota_query = mysql_query("SELECT DISTINCT kabkota FROM anggota WHERE kabkota != '' ORDER BY kabkota");
                while ($kab = mysql_fetch_assoc($kabkota_query)):
                ?>
                <option value="<?php echo htmlspecialchars($kab['kabkota']); ?>">
                    <?php echo htmlspecialchars($kab['kabkota']); ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label fw-medium">Cari</label>
            <div class="input-group">
                <input type="text" class="form-control" id="searchInput" placeholder="Nama, No. Anggota...">
                <button class="btn btn-outline-secondary" type="button" id="resetFilters">
                    <i data-lucide="x" width="16"></i>
                </button>
            </div>
        </div>
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small" id="filterInfo">
                    Menampilkan semua <?php echo $total_data; ?> anggota
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ==================== STATS ==================== -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="stat-card p-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h4 class="fw-bold mb-0" id="totalCount"><?php echo $total_data; ?></h4>
                    <small class="text-muted">Total Anggota</small>
                </div>
                <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                    <i data-lucide="users" width="20"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card p-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h4 class="fw-bold mb-0" id="activeCount"><?php echo $aktif_count; ?></h4>
                    <small class="text-muted">Anggota Aktif</small>
                </div>
                <div class="stat-icon bg-success bg-opacity-10 text-success">
                    <i data-lucide="user-check" width="20"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card p-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h4 class="fw-bold mb-0" id="expiredCount"><?php echo $expired_count; ?></h4>
                    <small class="text-muted">Telah Kadaluarsa</small>
                </div>
                <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                    <i data-lucide="calendar-x" width="20"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card p-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <?php
                    // Hitung anggota yang akan kadaluarsa dalam 30 hari
                    $expiring_count = 0;
                    $next_month = date('Y-m-d', strtotime('+30 days'));
                    foreach ($all_members as $member) {
                        if ($member['aktif'] == 'Y') {
                            $expired = strtotime($member['tgl_expired']);
                            $today_time = strtotime($today);
                            $next_month_time = strtotime($next_month);
                            if ($expired >= $today_time && $expired <= $next_month_time) {
                                $expiring_count++;
                            }
                        }
                    }
                    ?>
                    <h4 class="fw-bold mb-0" id="expiringCount"><?php echo $expiring_count; ?></h4>
                    <small class="text-muted">Akan Kadaluarsa</small>
                </div>
                <div class="stat-icon bg-danger bg-opacity-10 text-danger">
                    <i data-lucide="alert-circle" width="20"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ==================== TABEL KEANGGOTAAN ==================== -->
<div class="card">
    <div class="p-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h5 class="fw-bold mb-0">Daftar Anggota</h5>
            <div class="text-muted small" id="showingInfo">
                Menampilkan 0 dari <?php echo $total_data; ?> anggota
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-membership" id="membershipTable">
                <thead>
                    <tr>
                        <th width="60">Avatar</th>
                        <th>No. Anggota & Nama</th>
                        <th width="150">Masa Berlaku</th>
                        <th width="150">Lokasi</th>
                        <th width="120">Status</th>
                        <th width="120">Terakhir Update</th>
                        <th width="140" class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody id="membershipTableBody">
                    <!-- Data akan diisi oleh JavaScript -->
                </tbody>
            </table>
        </div>
        
        <!-- ==================== PAGINATION CLIENT-SIDE ==================== -->
        <nav class="mt-4" id="paginationContainer" style="display: none;">
            <ul class="pagination pagination-custom justify-content-center" id="pagination">
                <!-- Pagination akan di-generate oleh JavaScript -->
            </ul>
        </nav>
        
        <!-- Empty State -->
        <div class="text-center py-5" id="emptyState" style="display: none;">
            <div class="text-muted">
                <i data-lucide="users" width="48" class="mb-2"></i>
                <p>Tidak ada data keanggotaan ditemukan</p>
                <button class="btn btn-sm btn-outline-primary mt-2" onclick="resetFilters()">
                    Reset Filter
                </button>
            </div>
        </div>
        
        <!-- Info Tambahan -->
        <div class="alert alert-info mt-3">
            <i data-lucide="info" class="me-2"></i>
            <small>
                <strong>Catatan:</strong> Data keanggotaan hanya untuk user dengan role 'member'. 
                Penambahan dan penghapusan data anggota dilakukan melalui manajemen pengguna.
                Periode keanggotaan adalah 1 tahun sejak tanggal daftar/perpanjangan terakhir.
            </small>
        </div>
    </div>
</div>

<script>
// Data anggota dari PHP
const allMembers = <?php echo json_encode($all_members); ?>;
let currentPage = 1;
const itemsPerPage = 4;
let filteredMembers = [...allMembers];

// Elemen DOM
const searchInput = document.getElementById('searchInput');
const filterStatus = document.getElementById('filterStatus');
const filterProvinsi = document.getElementById('filterProvinsi');
const filterKabkota = document.getElementById('filterKabkota');
const resetFiltersBtn = document.getElementById('resetFilters');
const membershipTableBody = document.getElementById('membershipTableBody');
const filterInfo = document.getElementById('filterInfo');
const showingInfo = document.getElementById('showingInfo');
const totalCount = document.getElementById('totalCount');
const activeCount = document.getElementById('activeCount');
const expiredCount = document.getElementById('expiredCount');
const expiringCount = document.getElementById('expiringCount');
const paginationContainer = document.getElementById('paginationContainer');
const pagination = document.getElementById('pagination');
const emptyState = document.getElementById('emptyState');

// Fungsi untuk menentukan status keanggotaan
function getMembershipStatus(aktif, tgl_expired) {
    const today = new Date();
    const expiredDate = new Date(tgl_expired);
    
    if (aktif !== 'Y') {
        return { class: 'badge-inactive', text: 'Non-Aktif' };
    }
    
    if (expiredDate < today) {
        return { class: 'badge-expired', text: 'Kadaluarsa' };
    }
    
    const daysLeft = Math.floor((expiredDate - today) / (1000 * 60 * 60 * 24));
    
    if (daysLeft <= 30 && daysLeft > 0) {
        return { class: 'badge-expiring', text: `Akan Kadaluarsa (${daysLeft} hari)` };
    } else if (daysLeft > 30) {
        return { class: 'badge-active', text: 'Aktif' };
    } else {
        return { class: 'badge-expired', text: 'Kadaluarsa' };
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    // Event listeners untuk filter real-time
    searchInput.addEventListener('input', filterMembers);
    filterStatus.addEventListener('change', filterMembers);
    filterProvinsi.addEventListener('change', filterMembers);
    filterKabkota.addEventListener('change', filterMembers);
    resetFiltersBtn.addEventListener('click', resetFilters);
    
    // Setup mobile responsive labels
    setupMobileLabels();
    
    // Initial render
    renderTable();
    updateStats();
    
    // Update icons setelah render
    setTimeout(() => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }, 100);
});

// Filter anggota secara real-time
function filterMembers() {
    const searchTerm = searchInput.value.toLowerCase();
    const statusValue = filterStatus.value;
    const provinsiValue = filterProvinsi.value.toLowerCase();
    const kabkotaValue = filterKabkota.value.toLowerCase();
    
    filteredMembers = allMembers.filter(member => {
        // Filter berdasarkan pencarian
        const matchesSearch = !searchTerm || 
            member.nama_lengkap.toLowerCase().includes(searchTerm) ||
            member.no_anggota.toLowerCase().includes(searchTerm) ||
            (member.institusi && member.institusi.toLowerCase().includes(searchTerm));
        
        // Filter berdasarkan status
        let matchesStatus = true;
        if (statusValue) {
            const today = new Date();
            const expiredDate = new Date(member.tgl_expired);
            const daysLeft = Math.floor((expiredDate - today) / (1000 * 60 * 60 * 24));
            
            switch(statusValue) {
                case 'aktif':
                    matchesStatus = member.aktif === 'Y' && daysLeft > 0;
                    break;
                case 'nonaktif':
                    matchesStatus = member.aktif !== 'Y';
                    break;
                case 'expired':
                    matchesStatus = member.aktif === 'Y' && daysLeft <= 0;
                    break;
                case 'expiring':
                    matchesStatus = member.aktif === 'Y' && daysLeft > 0 && daysLeft <= 30;
                    break;
            }
        }
        
        // Filter berdasarkan provinsi
        const matchesProvinsi = !provinsiValue || 
            (member.provinsi && member.provinsi.toLowerCase().includes(provinsiValue));
        
        // Filter berdasarkan kab/kota
        const matchesKabkota = !kabkotaValue || 
            (member.kabkota && member.kabkota.toLowerCase().includes(kabkotaValue));
        
        return matchesSearch && matchesStatus && matchesProvinsi && matchesKabkota;
    });
    
    currentPage = 1; // Reset ke halaman pertama
    renderTable();
    updateStats();
    updateFilterInfo();
}

// Render tabel dengan pagination
function renderTable() {
    if (filteredMembers.length === 0) {
        membershipTableBody.innerHTML = '';
        paginationContainer.style.display = 'none';
        emptyState.style.display = 'block';
        showingInfo.textContent = `Menampilkan 0 dari ${filteredMembers.length} anggota`;
        return;
    }
    
    emptyState.style.display = 'none';
    
    // Hitung pagination
    const totalPages = Math.ceil(filteredMembers.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, filteredMembers.length);
    const currentMembers = filteredMembers.slice(startIndex, endIndex);
    
    // Render rows
    let html = '';
    currentMembers.forEach(member => {
        const avatarLetter = member.nama_lengkap.charAt(0).toUpperCase();
        const updatedDate = formatDate(new Date(member.updated));
        const tglDaftar = formatDate(new Date(member.tgl_daftar));
        
        const tglExpired = new Date(member.tgl_expired);
        const today = new Date();
        const daysLeft = Math.floor((tglExpired - today) / (1000 * 60 * 60 * 24));
        const daysText = daysLeft > 0 ? `${daysLeft} hari lagi` : 
                        (daysLeft < 0 ? `${Math.abs(daysLeft)} hari lalu` : 'Hari ini');
        
        const status = getMembershipStatus(member.aktif, member.tgl_expired);
        
        html += `
        <tr class="membership-row" 
            data-status="${member.aktif}" 
            data-expired="${member.tgl_expired}"
            data-name="${member.nama_lengkap.toLowerCase()}"
            data-noanggota="${member.no_anggota.toLowerCase()}"
            data-provinsi="${member.provinsi ? member.provinsi.toLowerCase() : ''}"
            data-kabkota="${member.kabkota ? member.kabkota.toLowerCase() : ''}">
            <td data-label="Avatar">
                <div class="membership-avatar">
                    ${avatarLetter}
                </div>
            </td>
            <td data-label="No. Anggota & Nama">
                <div class="membership-info">
                    <div class="membership-no">${escapeHtml(member.no_anggota)}</div>
                    <div class="membership-name">${escapeHtml(member.nama_lengkap)}</div>
                    ${member.institusi ? `<small class="text-muted">${escapeHtml(member.institusi)}</small>` : ''}
                </div>
            </td>
            <td data-label="Masa Berlaku">
                <div class="date-info">
                    <div class="date-main">
                        ${formatDateLong(tglExpired)}
                    </div>
                    <div class="date-days">
                        ${daysText}
                    </div>
                    <div class="small text-muted">
                        Daftar: ${tglDaftar}
                    </div>
                </div>
            </td>
            <td data-label="Lokasi">
                <div class="location-info">
                    ${member.kabkota ? `<div class="location-main">${escapeHtml(member.kabkota)}</div>` : ''}
                    ${member.provinsi ? `<div class="location-detail">${escapeHtml(member.provinsi)}</div>` : ''}
                    ${!member.kabkota && !member.provinsi ? '<span class="text-muted small">Belum diisi</span>' : ''}
                </div>
            </td>
            <td data-label="Status">
                <span class="status-badge ${status.class}">
                    ${status.text}
                </span>
            </td>
            <td data-label="Update">
                <div class="small text-muted">
                    ${updatedDate}
                </div>
            </td>
            <td class="text-center" data-label="Aksi">
                <div class="action-buttons-vertical">
                    <a href="membership-edit?id=${member.id_user}" class="btn btn-sm btn-outline-primary" title="Edit">
                        <i data-lucide="edit-2" width="14"></i>
                        <span class="d-none d-md-inline">Edit</span>
                    </a>
                    <a href="membership-edit?id=${member.id_user}&renew=1" class="btn btn-sm btn-outline-info" title="Perpanjang">
                        <i data-lucide="refresh-cw" width="14"></i>
                        <span class="d-none d-md-inline">Perpanjang</span>
                    </a>
                </div>
            </td>
        </tr>`;
    });
    
    membershipTableBody.innerHTML = html;
    
    // Update showing info
    showingInfo.textContent = `Menampilkan ${startIndex + 1}-${endIndex} dari ${filteredMembers.length} anggota`;
    
    // Render pagination
    renderPagination(totalPages);
    
    // Update icons
    setTimeout(() => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }, 100);
    
    // Setup mobile labels setelah render
    setupMobileLabels();
}

// Helper untuk format date (dd/mm/yyyy)
function formatDate(date) {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
}

// Helper untuk format date long (d MMM yyyy)
function formatDateLong(date) {
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
    return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
}

// Helper untuk escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Render pagination
function renderPagination(totalPages) {
    let html = '';
    
    // Previous button
    html += `
    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1}); return false;">
            <i data-lucide="chevron-left" width="14"></i>
        </a>
    </li>`;
    
    // Page numbers
    const maxPagesToShow = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
    let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
    
    if (endPage - startPage + 1 < maxPagesToShow) {
        startPage = Math.max(1, endPage - maxPagesToShow + 1);
    }
    
    // First page
    if (startPage > 1) {
        html += `
        <li class="page-item">
            <a class="page-link" href="#" onclick="changePage(1); return false;">1</a>
        </li>`;
        if (startPage > 2) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }
    
    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
        html += `
        <li class="page-item ${i === currentPage ? 'active' : ''}">
            <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
        </li>`;
    }
    
    // Last page
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        html += `
        <li class="page-item">
            <a class="page-link" href="#" onclick="changePage(${totalPages}); return false;">${totalPages}</a>
        </li>`;
    }
    
    // Next button
    html += `
    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1}); return false;">
            <i data-lucide="chevron-right" width="14"></i>
        </a>
    </li>`;
    
    pagination.innerHTML = html;
    
    // Tampilkan pagination hanya jika lebih dari 1 halaman
    if (totalPages > 1) {
        paginationContainer.style.display = 'block';
    } else {
        paginationContainer.style.display = 'none';
    }
}

// Change page
function changePage(page) {
    if (page < 1 || page > Math.ceil(filteredMembers.length / itemsPerPage)) return;
    currentPage = page;
    renderTable();
    // Scroll ke atas tabel
    document.querySelector('.card').scrollIntoView({ behavior: 'smooth' });
}

// Update statistik berdasarkan filter
function updateStats() {
    const today = new Date();
    const nextMonth = new Date();
    nextMonth.setDate(today.getDate() + 30);
    
    let totalActive = 0;
    let totalExpired = 0;
    let totalExpiring = 0;
    
    filteredMembers.forEach(member => {
        if (member.aktif === 'Y') {
            const expiredDate = new Date(member.tgl_expired);
            
            if (expiredDate < today) {
                totalExpired++;
            } else {
                totalActive++;
                
                // Cek apakah akan kadaluarsa dalam 30 hari
                if (expiredDate <= nextMonth) {
                    totalExpiring++;
                }
            }
        }
    });
    
    totalCount.textContent = filteredMembers.length;
    activeCount.textContent = totalActive;
    expiredCount.textContent = totalExpired;
    expiringCount.textContent = totalExpiring;
}

// Update filter info
function updateFilterInfo() {
    const statusText = filterStatus.value ? 
        (filterStatus.value === 'aktif' ? 'Aktif' : 
         filterStatus.value === 'nonaktif' ? 'Non-Aktif' :
         filterStatus.value === 'expired' ? 'Kadaluarsa' : 'Akan Kadaluarsa') : null;
    const provinsiText = filterProvinsi.value ? `Provinsi: ${filterProvinsi.value}` : null;
    const kabkotaText = filterKabkota.value ? `Kab/Kota: ${filterKabkota.value}` : null;
    const searchText = searchInput.value ? `"${searchInput.value}"` : null;
    
    const filters = [];
    if (statusText) filters.push(`Status: ${statusText}`);
    if (provinsiText) filters.push(provinsiText);
    if (kabkotaText) filters.push(kabkotaText);
    if (searchText) filters.push(`Pencarian: ${searchText}`);
    
    if (filters.length > 0) {
        filterInfo.textContent = `Filter aktif: ${filters.join(', ')}`;
    } else {
        filterInfo.textContent = `Menampilkan semua ${filteredMembers.length} anggota`;
    }
}
  
// Reset semua filter
function resetFilters() {
    searchInput.value = '';
    filterStatus.value = '';
    filterProvinsi.value = '';
    filterKabkota.value = '';
    filterMembers();
}

// Setup mobile responsive labels
function setupMobileLabels() {
    if (window.innerWidth <= 768) {
        const labels = ['Avatar', 'No. Anggota & Nama', 'Masa Berlaku', 'Lokasi', 'Status', 'Update', 'Aksi'];
        document.querySelectorAll('#membershipTableBody td').forEach((td, index) => {
            const labelIndex = index % 7;
            td.setAttribute('data-label', labels[labelIndex]);
        });
    }
}

// Responsive untuk window resize
window.addEventListener('resize', setupMobileLabels);

// Initial call untuk menampilkan data
document.addEventListener('DOMContentLoaded', function() {
    // Jika ada data, render tabel
    if (allMembers.length > 0) {
        renderTable();
    } else {
        membershipTableBody.innerHTML = '';
        emptyState.style.display = 'block';
        paginationContainer.style.display = 'none';
    }
});
</script>