<?php
// ==================== PROSES HAPUS PENGGUNA ====================
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if ($id > 0) {
        // Jangan hapus admin utama (id=1)
        if ($id != 1) {
            // Hapus data anggota terlebih dahulu jika ada
            mysql_query("DELETE FROM anggota WHERE id_user = '$id'");
            
            // Kemudian hapus user
            mysql_query("DELETE FROM user WHERE id = '$id' AND idweb = '$idweb'");
            
            $_SESSION['success_message'] = "Pengguna berhasil dihapus!";
        } else {
            $_SESSION['error_message'] = "Tidak dapat menghapus admin utama!";
        }
        header("Location: users-manage"); 
    }
}
// ==================== QUERY DATA ====================
$query = mysql_query("SELECT * FROM user WHERE idweb = '$idweb' ORDER BY role DESC, nama ASC");
$all_users = [];
while ($row = mysql_fetch_assoc($query)) {
    $all_users[] = $row;
}
$total_data = count($all_users);
?>
<!-- ==================== 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>
    .user-card {
        transition: all 0.3s ease;
        border: 1px solid var(--gray-200);
    }
    
    .user-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-admin {
        background-color: #f3e8ff;
        color: #7c3aed;
        border: 1px solid #e9d5ff;
    }
    
    .badge-member {
        background-color: #dbeafe;
        color: #1e40af;
        border: 1px solid #bfdbfe;
    }
    
    .table-user {
        font-size: 0.95rem;
    }
    
    .table-user th {
        background-color: #f8fafc;
        font-weight: 600;
        color: #334155;
        border-bottom: 2px solid #e2e8f0;
    }
    
    .table-user 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: 100px;
        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;
    }
    
    .user-info {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }
    
    .user-name {
        font-weight: 500;
        color: #1e293b;
    }
    
    .user-username {
        color: #64748b;
        font-size: 0.85rem;
    }
    
    /* Mobile Responsive */
    @media (max-width: 768px) {
        .table-responsive {
            border: 0;
        }
        
        .table-user thead {
            display: none;
        }
        
        .table-user tbody tr {
            display: block;
            margin-bottom: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 8px;
        }
        
        .table-user tbody td {
            display: block;
            text-align: left !important;
            border: none;
            padding: 0.75rem;
            position: relative;
            padding-left: 45%;
        }
        
        .table-user tbody td:before {
            content: attr(data-label);
            position: absolute;
            left: 1rem;
            width: 40%;
            font-weight: 600;
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .table-user tbody td:first-child {
            padding-top: 1rem;
            background-color: rgba(0,0,0,0.02);
            border-bottom: 1px solid #dee2e6;
        }
        
        .table-user tbody td:last-child {
            padding-bottom: 1rem;
        }
        
        .action-buttons-vertical {
            align-items: flex-start;
        }
        
        .action-buttons-vertical .btn {
            max-width: 100%;
        }
    }
    
    .user-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;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Manajemen Pengguna</h4>
        <p class="text-muted mb-0">Kelola pengguna dan akses sistem PAPENTARA</p>
    </div>
    <div>
        <a href="users-add/" class="btn btn-primary">
            <i data-lucide="user-plus" width="16"></i>
            Tambah 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 Pengguna</h6>
    <div class="row g-3">
        <div class="col-md-4">
            <label class="form-label fw-medium">Role</label>
            <select class="form-select" id="filterRole">
                <option value="">Semua Role</option>
                <option value="admin">Admin</option>
                <option value="member">Member</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label fw-medium">Status</label>
            <select class="form-select" id="filterStatus">
                <option value="">Semua Status</option>
                <option value="1">Aktif</option>
                <option value="0">Non-Aktif</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label fw-medium">Cari</label>
            <div class="input-group">
                <input type="text" class="form-control" id="searchInput" placeholder="Nama, Username, atau Email...">
                <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; ?> pengguna
                </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 Pengguna</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>
                    <?php
                    $admin_count = 0;
                    foreach ($all_users as $user) {
                        if ($user['role'] == 'admin') $admin_count++;
                    }
                    ?>
                    <h4 class="fw-bold mb-0" id="adminCount"><?php echo $admin_count; ?></h4>
                    <small class="text-muted">Admin</small>
                </div>
                <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                    <i data-lucide="shield" 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
                    $active_count = 0;
                    foreach ($all_users as $user) {
                        if ($user['status'] == 1) $active_count++;
                    }
                    ?>
                    <h4 class="fw-bold mb-0" id="activeCount"><?php echo $active_count; ?></h4>
                    <small class="text-muted">Pengguna 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>
                    <?php
                    $member_count = 0;
                    foreach ($all_users as $user) {
                        if ($user['role'] == 'member') $member_count++;
                    }
                    ?>
                    <h4 class="fw-bold mb-0" id="memberCount"><?php echo $member_count; ?></h4>
                    <small class="text-muted">Member</small>
                </div>
                <div class="stat-icon bg-info bg-opacity-10 text-info">
                    <i data-lucide="user" width="20"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ==================== TABEL PENGGUNA ==================== -->
<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 Pengguna</h5>
            <div class="text-muted small" id="showingInfo">
                Menampilkan 0 dari <?php echo $total_data; ?> pengguna
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-user" id="userTable">
                <thead>
                    <tr>
                        <th width="60">Avatar</th>
                        <th>Nama & Username</th>
                        <th width="100">Role</th>
                        <th width="120">Kontak</th>
                        <th width="100">Status</th>
                        <th width="120">Terakhir Update</th>
                        <th width="140" class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 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="user-x" width="48" class="mb-2"></i>
                <p>Tidak ada pengguna ditemukan</p>
                <button class="btn btn-sm btn-outline-primary mt-2" onclick="resetFilters()">
                    Reset Filter
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Data pengguna dari PHP
const allUsers = <?php echo json_encode($all_users); ?>;
let currentPage = 1;
const itemsPerPage = 4;
let filteredUsers = [...allUsers];

// Elemen DOM
const searchInput = document.getElementById('searchInput');
const filterRole = document.getElementById('filterRole');
const filterStatus = document.getElementById('filterStatus');
const resetFiltersBtn = document.getElementById('resetFilters');
const userTableBody = document.getElementById('userTableBody');
const filterInfo = document.getElementById('filterInfo');
const showingInfo = document.getElementById('showingInfo');
const totalCount = document.getElementById('totalCount');
const adminCount = document.getElementById('adminCount');
const activeCount = document.getElementById('activeCount');
const memberCount = document.getElementById('memberCount');
const paginationContainer = document.getElementById('paginationContainer');
const pagination = document.getElementById('pagination');
const emptyState = document.getElementById('emptyState');

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    // Event listeners untuk filter real-time
    searchInput.addEventListener('input', filterUsers);
    filterRole.addEventListener('change', filterUsers);
    filterStatus.addEventListener('change', filterUsers);
    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 pengguna secara real-time
function filterUsers() {
    const searchTerm = searchInput.value.toLowerCase();
    const roleValue = filterRole.value;
    const statusValue = filterStatus.value;
    
    filteredUsers = allUsers.filter(user => {
        // Filter berdasarkan pencarian
        const matchesSearch = !searchTerm || 
            user.nama.toLowerCase().includes(searchTerm) ||
            user.username.toLowerCase().includes(searchTerm) ||
            (user.email && user.email.toLowerCase().includes(searchTerm)) ||
            (user.institusi && user.institusi.toLowerCase().includes(searchTerm));
        
        // Filter berdasarkan role
        const matchesRole = !roleValue || user.role === roleValue;
        
        // Filter berdasarkan status
        const matchesStatus = !statusValue || user.status.toString() === statusValue;
        
        return matchesSearch && matchesRole && matchesStatus;
    });
    
    currentPage = 1; // Reset ke halaman pertama
    renderTable();
    updateStats();
    updateFilterInfo();
}

// Render tabel dengan pagination
function renderTable() {
    if (filteredUsers.length === 0) {
        userTableBody.innerHTML = '';
        paginationContainer.style.display = 'none';
        emptyState.style.display = 'block';
        showingInfo.textContent = `Menampilkan 0 dari ${filteredUsers.length} pengguna`;
        return;
    }
    
    emptyState.style.display = 'none';
    
    // Hitung pagination
    const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, filteredUsers.length);
    const currentUsers = filteredUsers.slice(startIndex, endIndex);
    
    // Render rows
    let html = '';
    currentUsers.forEach(user => {
        const avatarLetter = user.nama.charAt(0).toUpperCase();
        const updatedDate = user.updated === '0000-00-00 00:00:00' ? '-' : 
            formatDate(new Date(user.updated));
        
        html += `
        <tr class="user-row" 
            data-role="${user.role}" 
            data-status="${user.status}"
            data-name="${user.nama.toLowerCase()}"
            data-username="${user.username.toLowerCase()}"
            data-email="${user.email ? user.email.toLowerCase() : ''}">
            <td data-label="Avatar">
                <div class="user-avatar">
                    ${avatarLetter}
                </div>
            </td>
            <td data-label="Nama & Username">
                <div class="user-info">
                    <div class="user-name">${escapeHtml(user.nama)}</div>
                    <div class="user-username">@${escapeHtml(user.username)}</div>
                    ${user.institusi ? `<small class="text-muted">${escapeHtml(user.institusi)}</small>` : ''}
                </div>
            </td>
            <td data-label="Role">
                ${getRoleBadge(user.role)}
            </td>
            <td data-label="Kontak">
                <div class="small">
                    ${user.email ? `<div style="display: flex; align-items: center; gap: 4px;"><i data-lucide="mail" width="12"></i> ${escapeHtml(user.email)}</div>` : ''}
                    ${user.telpon ? `<div><i data-lucide="phone" width="12"></i> ${escapeHtml(user.telpon)}</div>` : ''}
                </div>
            </td>
            <td data-label="Status">
                ${getStatusBadge(user.status)}
            </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="users-edit?id=${user.id}" 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>
                    ${user.id != 1 ? `
                    <a href="users-manage?delete=${user.id}" class="btn btn-sm btn-outline-danger" 
                       onclick="return confirm('Hapus pengguna ini?')" title="Hapus">
                        <i data-lucide="trash-2" width="14"></i>
                        <span class="d-none d-md-inline">Hapus</span>
                    </a>
                    ` : ''}
                </div>
            </td>
        </tr>`;
    });
    
    userTableBody.innerHTML = html;
    
    // Update showing info
    showingInfo.textContent = `Menampilkan ${startIndex + 1}-${endIndex} dari ${filteredUsers.length} pengguna`;
    
    // Render pagination
    renderPagination(totalPages);
    
    // Update icons
    setTimeout(() => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }, 100);
    
    // Setup mobile labels setelah render
    setupMobileLabels();
}

// Helper untuk format date
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 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(filteredUsers.length / itemsPerPage)) return;
    currentPage = page;
    renderTable();
    // Scroll ke atas tabel
    document.querySelector('.card').scrollIntoView({ behavior: 'smooth' });
}

// Update statistik berdasarkan filter
function updateStats() {
    let totalAdmin = 0;
    let totalActive = 0;
    let totalMember = 0;
    
    filteredUsers.forEach(user => {
        if (user.role === 'admin') totalAdmin++;
        if (user.status == 1) totalActive++;
        if (user.role === 'member') totalMember++;
    });
    
    totalCount.textContent = filteredUsers.length;
    adminCount.textContent = totalAdmin;
    activeCount.textContent = totalActive;
    memberCount.textContent = totalMember;
}

// Update filter info
function updateFilterInfo() {
    const roleText = filterRole.value ? 
        (filterRole.value === 'admin' ? 'Admin' : 'Member') : null;
    const statusText = filterStatus.value ? 
        (filterStatus.value === '1' ? 'Aktif' : 'Non-Aktif') : null;
    const searchText = searchInput.value ? `"${searchInput.value}"` : null;
    
    const filters = [];
    if (roleText) filters.push(`Role: ${roleText}`);
    if (statusText) filters.push(`Status: ${statusText}`);
    if (searchText) filters.push(`Pencarian: ${searchText}`);
    
    if (filters.length > 0) {
        filterInfo.textContent = `Filter aktif: ${filters.join(', ')}`;
    } else {
        filterInfo.textContent = `Menampilkan semua ${filteredUsers.length} pengguna`;
    }
}
  
// Reset semua filter
function resetFilters() {
    searchInput.value = '';
    filterRole.value = '';
    filterStatus.value = '';
    filterUsers();
}

// Helper functions
function getRoleBadge(role) {
    switch(role) {
        case 'admin': return '<span class="badge-admin status-badge">Admin</span>';
        case 'member': return '<span class="badge-member status-badge">Member</span>';
        default: return '<span class="badge-member status-badge">Member</span>';
    }
}

function getStatusBadge(status) {
    return status == 1 
        ? '<span class="badge-active status-badge">Aktif</span>'
        : '<span class="badge-inactive status-badge">Non-Aktif</span>';
}

// Setup mobile responsive labels
function setupMobileLabels() {
    if (window.innerWidth <= 768) {
        const labels = ['Avatar', 'Nama & Username', 'Role', 'Kontak', 'Status', 'Update', 'Aksi'];
        document.querySelectorAll('#userTableBody 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 (allUsers.length > 0) {
        renderTable();
    } else {
        userTableBody.innerHTML = '';
        emptyState.style.display = 'block';
        paginationContainer.style.display = 'none';
    }
});
</script>