<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();
$tahun_ajaran = getTahunAjaranAktif();
$tahun_ajaran_id = $tahun_ajaran ? $tahun_ajaran['id_tahun_ajaran'] : 0;

// Query dengan struktur tabel yang benar - MENAMPILKAN SEMUA STATUS
$query = "SELECT s.*, 
          k.nama_kelas, 
          k.id_kelas as current_kelas_id,
          u.username,
          u.is_active as user_active
          FROM bkcare_siswa s
          LEFT JOIN bkcare_siswa_kelas sk ON s.id_siswa = sk.id_siswa AND sk.status = 'aktif'
          LEFT JOIN bkcare_kelas k ON sk.id_kelas = k.id_kelas
          LEFT JOIN bkcare_users u ON s.id_user = u.id_user
          ORDER BY 
          CASE s.status
              WHEN 'aktif' THEN 1
              WHEN 'lulus' THEN 2
              WHEN 'pindah' THEN 3
              ELSE 4
          END,
          s.nama ASC";
$result = mysqli_query($conn, $query);

if (!$result) {
    die("Error query: " . mysqli_error($conn));
}

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-user-graduate text-purple-600 mr-3"></i>
                Data Siswa
            </h1>
            <p class="text-gray-600 text-sm mt-1">Kelola data siswa (semua status)</p>
        </div>
        <div class="mt-3 md:mt-0 flex space-x-2">
            <a href="tambah.php" class="btn-primary">
                <i class="fas fa-plus mr-2"></i>Tambah Siswa
            </a>
        </div>
    </div>

    <!-- Success Alert -->
    <?php if (isset($_SESSION['success_message'])): ?>
    <div id="success-alert" class="mb-6 rounded-lg p-4 bg-green-50 border-l-4 border-green-500 shadow-md">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-500 text-xl"></i>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-medium text-green-800"><?= $_SESSION['success_title'] ?? 'Berhasil!' ?></h3>
                <div class="mt-1 text-sm text-green-700"><?= $_SESSION['success_message'] ?></div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-green-500 hover:text-green-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    <?php 
    unset($_SESSION['success_message']);
    unset($_SESSION['success_title']);
    endif; 
    ?>

    <!-- Error Alert -->
    <?php if (isset($_SESSION['error_message'])): ?>
    <div id="error-alert" class="mb-6 rounded-lg p-4 bg-red-50 border-l-4 border-red-500 shadow-md">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-medium text-red-800"><?= $_SESSION['error_title'] ?? 'Gagal!' ?></h3>
                <div class="mt-1 text-sm text-red-700"><?= $_SESSION['error_message'] ?></div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-red-500 hover:text-red-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    <?php 
    unset($_SESSION['error_message']);
    unset($_SESSION['error_title']);
    endif; 
    ?>

    <!-- Warning Alert -->
    <?php if (isset($_SESSION['warning_message'])): ?>
    <div id="warning-alert" class="mb-6 rounded-lg p-4 bg-yellow-50 border-l-4 border-yellow-500 shadow-md">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-medium text-yellow-800"><?= $_SESSION['warning_title'] ?? 'Peringatan!' ?></h3>
                <div class="mt-1 text-sm text-yellow-700"><?= $_SESSION['warning_message'] ?></div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-yellow-500 hover:text-yellow-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    <?php 
    unset($_SESSION['warning_message']);
    unset($_SESSION['warning_title']);
    endif; 
    ?>

    <!-- Filter & Search Card -->
    <div class="card-stat p-4 mb-6">
        <div class="flex flex-col md:flex-row justify-between items-center gap-4">
            <div class="flex flex-wrap items-center gap-2 w-full md:w-auto">
                <i class="fas fa-filter text-purple-600"></i>
                <span class="text-sm font-medium text-gray-700">Filter:</span>
                
                <select id="filterKelas" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none">
                    <option value="">Semua Kelas</option>
                    <?php
                    $kelas_query = mysqli_query($conn, "SELECT * FROM bkcare_kelas WHERE id_tahun_ajaran = '$tahun_ajaran_id' ORDER BY nama_kelas");
                    while ($kelas = mysqli_fetch_assoc($kelas_query)) {
                        echo "<option value='" . $kelas['id_kelas'] . "'>" . htmlspecialchars($kelas['nama_kelas']) . "</option>";
                    }
                    ?>
                </select>
                
                <select id="filterStatus" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none">
                    <option value="">Semua Status</option>
                    <option value="aktif">Aktif</option>
                    <option value="lulus">Lulus</option>
                    <option value="pindah">Pindah</option>
                </select>
                
                <button id="resetFilter" class="bg-gray-200 text-gray-700 px-3 py-2 rounded-lg text-sm hover:bg-gray-300 transition">
                    <i class="fas fa-undo mr-1"></i>Reset
                </button>
            </div>
            <div class="relative w-full md:w-64">
                <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input type="text" id="searchInput" placeholder="Cari nama atau NIS..." 
                       class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none">
            </div>
        </div>
    </div>

    <!-- Table -->
    <div class="card-stat p-6">
        <div class="overflow-x-auto">
            <table class="w-full" id="siswaTable">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">NIS</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama Siswa</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kelas</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jenis Kelamin</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No. HP</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Akun</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (mysqli_num_rows($result) > 0): ?>
                        <?php $no = 1; ?>
                        <?php while($row = mysqli_fetch_assoc($result)): ?>
                            <tr class="hover:bg-purple-50 transition siswa-row" 
                                data-kelas="<?= $row['current_kelas_id'] ?? '' ?>"
                                data-status="<?= $row['status'] ?>"
                                data-nama="<?= strtolower($row['nama']) ?>"
                                data-nis="<?= strtolower($row['nis']) ?>">
                                <td class="px-6 py-4 text-sm text-gray-600"><?= $no++ ?></td>
                                <td class="px-6 py-4 text-sm font-mono text-gray-600"><?= htmlspecialchars($row['nis']) ?></td>
                                <td class="px-6 py-4 text-sm font-medium text-gray-800">
                                    <div class="flex items-center">
                                        <div class="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center mr-2">
                                            <i class="fas fa-user-graduate text-purple-600 text-sm"></i>
                                        </div>
                                        <?= htmlspecialchars($row['nama']) ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['nama_kelas']): ?>
                                        <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-school mr-1"></i>
                                            <?= htmlspecialchars($row['nama_kelas']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-minus-circle mr-1"></i>Belum ditempatkan
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['jenis_kelamin'] == 'L'): ?>
                                        <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-mars mr-1"></i>Laki-laki
                                        </span>
                                    <?php else: ?>
                                        <span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-venus mr-1"></i>Perempuan
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php 
                                    $status_badge = [
                                        'aktif' => 'bg-green-100 text-green-800',
                                        'lulus' => 'bg-blue-100 text-blue-800',
                                        'pindah' => 'bg-yellow-100 text-yellow-800'
                                    ];
                                    $status_icon = [
                                        'aktif' => 'fas fa-check-circle',
                                        'lulus' => 'fas fa-graduation-cap',
                                        'pindah' => 'fas fa-exchange-alt'
                                    ];
                                    $badge_class = $status_badge[$row['status']] ?? 'bg-gray-100 text-gray-800';
                                    $icon = $status_icon[$row['status']] ?? 'fas fa-info-circle';
                                    ?>
                                    <span class="<?= $badge_class ?> px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                        <i class="<?= $icon ?> mr-1"></i>
                                        <?= ucfirst($row['status']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['no_hp']): ?>
                                        <span class="flex items-center">
                                            <i class="fab fa-whatsapp text-green-500 mr-1"></i>
                                            <?= htmlspecialchars($row['no_hp']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-gray-400">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['id_user']): ?>
                                        <span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center" 
                                              data-bs-toggle="tooltip" 
                                              title="Username: <?= $row['username'] ?>">
                                            <i class="fas fa-check-circle mr-1"></i>Aktif
                                        </span>
                                    <?php else: ?>
                                        <span class="bg-red-100 text-red-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-times-circle mr-1"></i>Tidak Ada
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-right">
                                    <a href="detail.php?id=<?= $row['id_siswa'] ?>" 
                                       class="text-blue-600 hover:text-blue-800 mx-1"
                                       data-bs-toggle="tooltip" 
                                       title="Detail Siswa">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit.php?id=<?= $row['id_siswa'] ?>" 
                                       class="text-green-600 hover:text-green-800 mx-1"
                                       data-bs-toggle="tooltip" 
                                       title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="#" 
                                       onclick="confirmAction(<?= $row['id_siswa'] ?>, '<?= htmlspecialchars($row['nama']) ?> (NIS: <?= $row['nis'] ?>)', '<?= $row['status'] ?>')"
                                       class="text-red-600 hover:text-red-800 mx-1"
                                       data-bs-toggle="tooltip" 
                                       title="Hapus/Nonaktifkan">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-user-graduate text-5xl mb-3 text-gray-300"></i>
                                <p class="text-lg font-medium">Belum ada data siswa</p>
                                <p class="text-sm mt-1">Klik tombol "Tambah Siswa" untuk menambahkan data</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Modal Konfirmasi Aksi -->
<div class="modal fade" id="actionModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-2xl">
            <div class="modal-header" id="actionModalHeader">
                <h5 class="modal-title" id="actionModalTitle">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Konfirmasi
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-6">
                <p class="text-gray-600 mb-2" id="actionModalMessage"></p>
                <p class="font-semibold text-gray-800" id="actionItemInfo"></p>
                <div id="actionModalWarning" class="text-sm text-orange-600 mt-3">
                    <i class="fas fa-info-circle mr-1"></i>
                    <span id="actionWarningText"></span>
                </div>
            </div>
            <div class="modal-footer border-t border-gray-100 p-4">
                <button type="button" class="btn-outline-primary text-sm" data-bs-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Batal
                </button>
                <a href="#" id="confirmActionBtn" class="px-6 py-2 rounded-full transition text-sm">
                    <i class="fas fa-check mr-1"></i>Ya, Lanjutkan
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Filter dan Search functionality
$(document).ready(function() {
    // Panggil applyFilters saat halaman dimuat
    applyFilters();
    
    // Filter by kelas
    $('#filterKelas').on('change', function() {
        applyFilters();
    });
    
    // Filter by status
    $('#filterStatus').on('change', function() {
        applyFilters();
    });

    // Search by name or NIS
    $('#searchInput').on('keyup', function() {
        applyFilters();
    });
    
    // Reset filter
    $('#resetFilter').on('click', function() {
        $('#filterKelas').val('');
        $('#filterStatus').val('');
        $('#searchInput').val('');
        applyFilters();
    });
    
    function applyFilters() {
        var kelasId = $('#filterKelas').val();
        var statusFilter = $('#filterStatus').val();
        var searchValue = $('#searchInput').val().toLowerCase().trim();
        var visibleCount = 0;
        
        $('.siswa-row').each(function() {
            var showByKelas = true;
            var showByStatus = true;
            var showBySearch = true;
            
            // Filter by kelas
            if (kelasId !== '') {
                var rowKelas = $(this).data('kelas') || '';
                showByKelas = (rowKelas == kelasId);
            }
            
            // Filter by status
            if (statusFilter !== '') {
                var rowStatus = $(this).data('status');
                showByStatus = (rowStatus == statusFilter);
            }
            
            // Filter by search
            if (searchValue !== '') {
                var nama = $(this).data('nama') || '';
                var nis = $(this).data('nis') || '';
                showBySearch = (nama.indexOf(searchValue) > -1 || nis.indexOf(searchValue) > -1);
            }
            
            // Show/hide based on all filters
            if (showByKelas && showByStatus && showBySearch) {
                $(this).show();
                visibleCount++;
            } else {
                $(this).hide();
            }
        });
        
        // Tampilkan pesan jika tidak ada data yang cocok
        if (visibleCount === 0 && $('.siswa-row').length > 0) {
            if ($('#no-data-message').length === 0) {
                $('#siswaTable tbody').append('<tr id="no-data-message"><td colspan="9" class="px-6 py-12 text-center text-gray-500"><i class="fas fa-search text-5xl mb-3 text-gray-300"></i><p class="text-lg font-medium">Tidak ada data yang cocok dengan filter</p><p class="text-sm mt-1">Coba gunakan filter atau kata kunci pencarian yang berbeda</p></td></tr>');
            }
        } else {
            $('#no-data-message').remove();
        }
    }

    // Auto hide alerts after 5 seconds
    setTimeout(function() {
        $('#success-alert, #error-alert, #warning-alert').fadeOut('slow');
    }, 5000);

    // Tooltip initialization
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Fungsi konfirmasi aksi (hapus/nonaktifkan)
function confirmAction(id, info, status) {
    var modal = new bootstrap.Modal(document.getElementById('actionModal'));
    var modalHeader = document.getElementById('actionModalHeader');
    var modalTitle = document.getElementById('actionModalTitle');
    var modalMessage = document.getElementById('actionModalMessage');
    var modalWarning = document.getElementById('actionModalWarning');
    var warningText = document.getElementById('actionWarningText');
    var confirmBtn = document.getElementById('confirmActionBtn');
    
    document.getElementById('actionItemInfo').textContent = info;
    
    if (status === 'aktif') {
        // Untuk siswa aktif, tawarkan nonaktifkan
        modalHeader.className = 'modal-header bg-yellow-500 text-white rounded-t-2xl';
        modalTitle.innerHTML = '<i class="fas fa-exclamation-triangle mr-2"></i>Nonaktifkan Siswa';
        modalMessage.textContent = 'Apakah Anda yakin ingin menonaktifkan siswa:';
        warningText.innerHTML = 'Siswa yang dinonaktifkan akan berstatus "Pindah" dan tidak muncul di data aktif, tetapi data terkait tetap tersimpan.';
        confirmBtn.href = 'nonaktifkan.php?id=' + id;
        confirmBtn.className = 'bg-yellow-500 text-white px-6 py-2 rounded-full hover:bg-yellow-600 transition text-sm';
        confirmBtn.innerHTML = '<i class="fas fa-power-off mr-1"></i>Ya, Nonaktifkan';
    } else {
        // Untuk siswa tidak aktif, tawarkan hapus permanent
        modalHeader.className = 'modal-header bg-red-500 text-white rounded-t-2xl';
        modalTitle.innerHTML = '<i class="fas fa-exclamation-triangle mr-2"></i>Hapus Permanen';
        modalMessage.textContent = 'PERHATIAN! Anda akan menghapus permanen siswa:';
        warningText.innerHTML = 'Data yang sudah dihapus tidak dapat dikembalikan! Semua data terkait akan ikut terhapus.';
        confirmBtn.href = 'hapus.php?id=' + id + '&force=1';
        confirmBtn.className = 'bg-red-500 text-white px-6 py-2 rounded-full hover:bg-red-600 transition text-sm';
        confirmBtn.innerHTML = '<i class="fas fa-trash mr-1"></i>Ya, Hapus Permanen';
    }
    
    modalWarning.style.display = 'block';
    modal.show();
}
</script>

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