<?php
// ==================== PROSES FILTERING & PAGINATION ====================
// Ambil semua data seminar aktif
$query = mysql_query("
    SELECT s.*, 
           DATE(s.waktu_mulai) as tanggal,
           DATE_FORMAT(s.waktu_mulai, '%H:%i') as jam_mulai,
           DATE_FORMAT(s.waktu_akhir, '%H:%i') as jam_akhir
    FROM seminar s 
    WHERE s.aktif = 'Y'
    ORDER BY s.waktu_mulai DESC
");

$all_seminars = [];
while ($row = mysql_fetch_assoc($query)) {
    // Tentukan status berdasarkan waktu
    $now = date('Y-m-d H:i:s');
    $status = ($row['waktu_akhir'] > $now) ? 'Open' : 'Selesai';
    
    // Format tipe/tipe seminar
    $type_map = [
        'online' => 'Webinar Zoom',
        'hybrid' => 'Hybrid',
        'offline' => 'Offline'
    ];
    $type = isset($type_map[$row['metode']]) ? $type_map[$row['metode']] : $row['metode'];
    
    // Format gambar
    $image = !empty($row['gambar']) ? $img . $row['gambar'] : 'https://images.unsplash.com/photo-1544531586-fde5298cdd40?auto=format&fit=crop&q=80&w=800';
    
    $all_seminars[] = [
        'id' => $row['id'],
        'kode_seminar' => $row['kode_seminar'],
        'judul' => $row['judul'],
        'image' => $image,
        'date' => date('Y-m-d', strtotime($row['waktu_mulai'])),
        'waktu_mulai' => $row['waktu_mulai'],
        'waktu_akhir' => $row['waktu_akhir'],
        'jam_mulai' => $row['jam_mulai'],
        'jam_akhir' => $row['jam_akhir'],
        'pemateri' => $row['pemateri'],
        'biaya_umum' => $row['biaya_umum'],
        'biaya_anggota' => $row['biaya_anggota'],
        'metode' => $row['metode'],
        'type' => $type,
        'status' => $status,
        'deskripsi' => $row['deskripsi'],
        'tanggal' => date('d M Y', strtotime($row['waktu_mulai'])),
        'jml_jam' => $row['jml_jam'],
        'jml_hari' => $row['jml_hari'],
        'aktif' => $row['aktif']
    ];
}
$total_data = count($all_seminars);
?>

<!-- ==================== STYLE TAMBAHAN ==================== -->
<style>
/* Tambahan CSS untuk tampilan */
.text-truncate-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.4;
    max-height: 2.8em;
}

.text-truncate-3 {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.4;
    max-height: 4.2em;
}

.hover-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    border: 1px solid rgba(0,0,0,0.08);
}

.hover-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.1) !important;
}

.object-fit-cover {
    object-fit: cover;
}

.badge-open {
    background-color: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}

.badge-selesai {
    background-color: #6b7280;
    color: white;
    border: none;
}

/* Filter card */
.filter-card {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 1.25rem;
    margin-bottom: 1.5rem;
}

/* Pagination */
.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;
}

/* Stats card */
.stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
    padding: 1.25rem;
    margin-bottom: 1.5rem;
}

.stat-card h4 {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

.stat-card small {
    opacity: 0.9;
    font-size: 0.875rem;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .text-truncate-2 {
        -webkit-line-clamp: 2;
    }
    
    .text-truncate-3 {
        -webkit-line-clamp: 3;
    }
    
    .pagination .page-link {
        padding: 0.375rem 0.5rem;
        font-size: 0.875rem;
        min-width: 32px;
    }
    
    .stat-card h4 {
        font-size: 1.5rem;
    }
}
</style>

<div class="container-xl py-5">
    <div class="text-center mb-5">
        <h2 class="fw-bold display-6">Katalog Seminar & Pelatihan</h2>
        <p class="text-muted lead">Pilih topik yang sesuai dengan kebutuhan pengembangan diri Anda.</p>
    </div>
    
    <!-- ==================== FILTER REAL-TIME ==================== -->
    <div class="filter-card">
        <h6 class="fw-bold mb-3">Filter Seminar</h6>
        <form method="GET" action="" id="filterForm">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label fw-medium">Cari Seminar</label>
                    <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                            <i data-lucide="search" width="18"></i>
                        </span>
                        <input type="text" id="searchInput" class="form-control bg-light border-start-0 ps-0" 
                               placeholder="Judul, pemateri, atau kode..." 
                               value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-medium">Status</label>
                    <select id="filterStatus" class="form-select bg-light">
                        <option value="all">Semua Status</option>
                        <option value="Open" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Open') ? 'selected' : ''; ?>>Open</option>
                        <option value="Selesai" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Selesai') ? 'selected' : ''; ?>>Selesai</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-medium">Tipe</label>
                    <select id="filterType" class="form-select bg-light">
                        <option value="all">Semua Tipe</option>
                        <option value="Webinar Zoom" <?php echo (isset($_GET['type']) && $_GET['type'] == 'Webinar Zoom') ? 'selected' : ''; ?>>Webinar Zoom</option>
                        <option value="Hybrid" <?php echo (isset($_GET['type']) && $_GET['type'] == 'Hybrid') ? 'selected' : ''; ?>>Hybrid</option>
                        <option value="Offline" <?php echo (isset($_GET['type']) && $_GET['type'] == 'Offline') ? 'selected' : ''; ?>>Offline</option>
                    </select>
                </div>
                <div class="col-12 mt-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted small" id="filterInfo">
                            Menampilkan semua <?php echo $total_data; ?> seminar
                        </div>
                        <div>
                            <div id="applyFilter"> </div>
                            <div id="resetFilters"> </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    
    <!-- ==================== SEMINAR LIST ==================== -->
    <div class="row g-4" id="seminarContainer">
        <!-- Data akan diisi oleh JavaScript -->
    </div>
    
    <!-- ==================== PAGINATION CLIENT-SIDE ==================== -->
    <nav class="mt-5" id="paginationContainer" style="display: none;">
        <ul class="pagination pagination-custom justify-content-center" id="pagination">
            <!-- Pagination akan di-generate oleh JavaScript -->
        </ul>
        <div class="text-center text-muted small mt-2" id="pageInfo">
            <!-- Info halaman akan diisi oleh JavaScript -->
        </div>
    </nav>
    
    <!-- ==================== EMPTY STATE ==================== -->
    <div id="seminar-empty-state" class="text-center py-5" style="display: none;">
        <div class="bg-light rounded-circle d-inline-flex p-3 mb-3">
            <i data-lucide="calendar-x" class="text-muted" width="48" height="48"></i>
        </div>
        <h5 class="fw-bold text-muted">Tidak ada seminar ditemukan</h5>
        <p class="text-muted">Coba ubah filter pencarian Anda</p>
        <button id="resetFilterBtn" class="btn btn-outline-primary mt-2">
            <i data-lucide="rotate-ccw" width="14" class="me-1"></i> Reset Filter
        </button>
    </div>
</div>

<script>
// ==================== VARIABEL GLOBAL ====================
const allSeminars = <?php echo json_encode($all_seminars); ?>;
let currentPage = 1;
const itemsPerPage = 6;
let filteredSeminars = [...allSeminars];

// ==================== ELEMEN DOM ====================
const searchInput = document.getElementById('searchInput');
const filterStatus = document.getElementById('filterStatus');
const filterType = document.getElementById('filterType');
const applyFilterBtn = document.getElementById('applyFilter');
const resetFiltersBtn = document.getElementById('resetFilters');
const resetFilterBtn = document.getElementById('resetFilterBtn');
const seminarContainer = document.getElementById('seminarContainer');
const filterInfo = document.getElementById('filterInfo');
const totalCount = document.getElementById('totalCount');
const openCount = document.getElementById('openCount');
const onlineCount = document.getElementById('onlineCount');
const todayCount = document.getElementById('todayCount');
const paginationContainer = document.getElementById('paginationContainer');
const pagination = document.getElementById('pagination');
const pageInfo = document.getElementById('pageInfo');
const emptyState = document.getElementById('seminar-empty-state');

// ==================== FUNGSI UTAMA ====================
function initFiltering() {
    // Event listeners untuk filter real-time
    searchInput.addEventListener('input', () => {
        setTimeout(filterSeminars, 300); // Debounce 300ms
    });
    
    filterStatus.addEventListener('change', filterSeminars);
    filterType.addEventListener('change', filterSeminars);
    applyFilterBtn.addEventListener('click', filterSeminars);
    resetFiltersBtn.addEventListener('click', resetFilters);
    resetFilterBtn.addEventListener('click', resetFilters);
    
    // Initial render
    filterSeminars();
    
    // Update icons
    setTimeout(() => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }, 100);
}

// Filter seminar secara real-time
function filterSeminars() {
    const searchTerm = searchInput.value.toLowerCase();
    const statusValue = filterStatus.value;
    const typeValue = filterType.value;
    
    filteredSeminars = allSeminars.filter(seminar => {
        // Filter berdasarkan pencarian
        const matchesSearch = !searchTerm || 
            seminar.judul.toLowerCase().includes(searchTerm) ||
            seminar.pemateri.toLowerCase().includes(searchTerm) ||
            seminar.kode_seminar.toLowerCase().includes(searchTerm);
        
        // Filter berdasarkan status
        const matchesStatus = statusValue === 'all' || seminar.status === statusValue;
        
        // Filter berdasarkan tipe
        const matchesType = typeValue === 'all' || seminar.type === typeValue;
        
        return matchesSearch && matchesStatus && matchesType;
    });
    
    currentPage = 1; // Reset ke halaman pertama
    renderSeminars();
    updateStats();
    updateFilterInfo();
    updateURL();
}

// Render seminar cards dengan pagination
function renderSeminars() {
    if (filteredSeminars.length === 0) {
        seminarContainer.innerHTML = '';
        paginationContainer.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }
    
    emptyState.style.display = 'none';
    
    // Hitung pagination
    const totalPages = Math.ceil(filteredSeminars.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, filteredSeminars.length);
    const currentSeminars = filteredSeminars.slice(startIndex, endIndex);
    
    // Render cards
    let html = '';
    currentSeminars.forEach(seminar => {
        // Format waktu
        const waktuMulai = new Date(seminar.waktu_mulai);
        const waktuAkhir = new Date(seminar.waktu_akhir);
        const timeStatus = getTimeStatus(seminar.waktu_mulai, seminar.waktu_akhir);
        
        html += `
        <div class="col-md-4">
            <div class="card h-100 border-0 shadow-sm hover-card overflow-hidden">
                <div class="position-relative" style="height: 200px;">
                    <img src="${escapeHtml(seminar.image)}" alt="${escapeHtml(seminar.judul)}" 
                         class="w-100 h-100 object-fit-cover">
                    <div class="position-absolute top-0 end-0 p-2">
                        <span class="badge ${timeStatus.class}">
                            ${timeStatus.label}
                        </span>
                    </div>
                </div>
                <div class="card-body d-flex flex-column p-4">
                    <div class="d-flex gap-3 text-muted small mb-2">
                        <span class="d-flex align-items-center gap-1">
                            <i data-lucide="calendar" width="14"></i> ${seminar.tanggal}
                        </span>
                        <span class="d-flex align-items-center gap-1">
                            <i data-lucide="video" width="14"></i> ${escapeHtml(seminar.type)}
                        </span>
                    </div>
                    <h5 class="card-title fw-bold mb-2 text-truncate-2">
                        ${escapeHtml(seminar.judul)}
                    </h5>
                    <p class="card-text text-muted small flex-grow-1 text-truncate-3">
                        ${escapeHtml(seminar.deskripsi)}
                    </p>
                    
                    <hr class="opacity-10 my-3">
                    
                    <div class="mb-3 d-flex justify-content-between align-items-end">
                        <div>
                            <small class="text-muted d-block" style="font-size: 0.7rem;">UMUM</small> 
                            <span class="text-decoration-line-through text-muted small">
                                Rp ${formatNumber(seminar.biaya_umum)}
                            </span>
                        </div>
                        <div class="text-end">
                            <small class="text-primary fw-bold d-block" style="font-size: 0.7rem;">MEMBER</small> 
                            <span class="text-primary fw-bold">
                                ${seminar.biaya_anggota == 0 ? 'GRATIS' : 'Rp ' + formatNumber(seminar.biaya_anggota)}
                            </span>
                        </div>
                    </div>

                    <a href="detail-seminar/?id=${seminar.id}" 
                       class="btn w-100 fw-medium ${seminar.status === 'Open' ? 'btn-primary' : 'btn-outline-secondary'} ${seminar.status !== 'Open' ? 'disabled' : ''}">
                        ${seminar.status === 'Open' ? 'Detail & Daftar' : 'Selesai'}
                    </a>
                </div>
            </div>
        </div>`;
    });
    
    seminarContainer.innerHTML = html;
    
    // Render pagination jika diperlukan
    if (totalPages > 1) {
        renderPagination(totalPages);
        paginationContainer.style.display = 'block';
        pageInfo.innerHTML = `Halaman ${currentPage} dari ${totalPages}`;
    } else {
        paginationContainer.style.display = 'none';
    }
    
    // Update icons
    setTimeout(() => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }, 100);
}

// Helper untuk menentukan status waktu
function getTimeStatus(waktu_mulai, waktu_akhir) {
    const now = new Date();
    const start = new Date(waktu_mulai);
    const end = new Date(waktu_akhir);
    
    if (now < start) {
        return { label: 'Mendatang', class: 'badge-mendatang' };
    } else if (now >= start && now <= end) {
        return { label: 'Berlangsung', class: 'badge-berlangsung' };
    } else {
        return { label: 'Selesai', class: 'badge-selesai' };
    }
}

// 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;
}

// Change page
function changePage(page) {
    if (page < 1 || page > Math.ceil(filteredSeminars.length / itemsPerPage)) return;
    currentPage = page;
    renderSeminars();
    window.scrollTo({ top: seminarContainer.offsetTop - 100, behavior: 'smooth' });
}

// Update statistik berdasarkan filter
function updateStats() {
    const now = new Date();
    const todayStr = now.toISOString().split('T')[0];
    
    let totalOpen = 0;
    let totalOnline = 0;
    let totalToday = 0;
    
    filteredSeminars.forEach(seminar => {
        if (seminar.status === 'Open') totalOpen++;
        if (seminar.metode === 'online') totalOnline++;
        
        const seminarDate = new Date(seminar.waktu_mulai).toISOString().split('T')[0];
        if (seminarDate === todayStr) totalToday++;
    });
    
    totalCount.textContent = filteredSeminars.length;
    openCount.textContent = totalOpen;
    onlineCount.textContent = totalOnline;
    todayCount.textContent = totalToday;
}

// Update filter info
function updateFilterInfo() {
    const statusText = filterStatus.value !== 'all' ? 
        (filterStatus.value === 'Open' ? 'Open' : 'Selesai') : null;
    
    const typeText = filterType.value !== 'all' ? filterType.value : null;
    
    const searchText = searchInput.value ? `"${searchInput.value}"` : null;
    
    const filters = [];
    if (statusText) filters.push(`Status: ${statusText}`);
    if (typeText) filters.push(`Tipe: ${typeText}`);
    if (searchText) filters.push(`Pencarian: ${searchText}`);
    
    if (filters.length > 0) {
        filterInfo.innerHTML = `Filter aktif: ${filters.join(', ')}<br>
                               Menampilkan ${filteredSeminars.length} dari ${allSeminars.length} seminar`;
    } else {
        filterInfo.textContent = `Menampilkan semua ${filteredSeminars.length} seminar`;
    }
}

// Reset semua filter
function resetFilters() {
    searchInput.value = '';
    filterStatus.value = 'all';
    filterType.value = 'all';
    filterSeminars();
    updateURL();
}

// Update URL dengan parameter filter
function updateURL() {
    const params = new URLSearchParams();
    
    if (searchInput.value) params.set('search', searchInput.value);
    if (filterStatus.value !== 'all') params.set('status', filterStatus.value);
    if (filterType.value !== 'all') params.set('type', filterType.value);
    if (currentPage > 1) params.set('page', currentPage);
    
    const newUrl = params.toString() ? `?${params.toString()}` : '?';
    window.history.replaceState({}, '', newUrl);
}

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

function formatNumber(num) {
    return new Intl.NumberFormat('id-ID').format(num);
}

// Initialize filter dari URL parameter
function initFromURL() {
    const urlParams = new URLSearchParams(window.location.search);
    
    if (urlParams.has('search')) {
        searchInput.value = urlParams.get('search');
    }
    
    if (urlParams.has('status')) {
        filterStatus.value = urlParams.get('status');
    }
    
    if (urlParams.has('type')) {
        filterType.value = urlParams.get('type');
    }
    
    if (urlParams.has('page')) {
        const page = parseInt(urlParams.get('page'));
        if (!isNaN(page) && page > 0) {
            currentPage = page;
        }
    }
}

// ==================== INISIALISASI ====================
document.addEventListener('DOMContentLoaded', function() {
    // Initialize dari URL parameter
    initFromURL();
    
    // Initialize filtering system
    initFiltering();
    
    // Update icons
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});
</script>