<?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;

// Pagination
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$filter_kelas = isset($_GET['filter_kelas']) ? (int)$_GET['filter_kelas'] : 0;
$filter_status = isset($_GET['filter_status']) ? mysqli_real_escape_string($conn, $_GET['filter_status']) : '';

// Build query
$where_clause = "WHERE 1=1";

if (!empty($search)) {
    $where_clause .= " AND (s.nis LIKE '%$search%' OR s.nama LIKE '%$search%' OR s.nama_orangtua LIKE '%$search%')";
}

if ($filter_kelas > 0) {
    $where_clause .= " AND sk.id_kelas = $filter_kelas";
}

if (!empty($filter_status)) {
    $where_clause .= " AND s.status = '$filter_status'";
}

// Get total records
$count_query = "SELECT COUNT(DISTINCT s.id_siswa) as total 
                FROM bkcare_siswa s
                LEFT JOIN bkcare_siswa_kelas sk ON s.id_siswa = sk.id_siswa AND sk.status = 'aktif'
                $where_clause";
$count_result = mysqli_query($conn, $count_query);
$total_records = mysqli_fetch_assoc($count_result)['total'];
$total_pages = ceil($total_records / $limit);

// Get siswa data
$query = "SELECT s.*, 
          u.username, 
          u.is_active as user_active,
          k.nama_kelas,
          sk.id_kelas as kelas_id,
          sk.status as status_kelas
          FROM bkcare_siswa s
          LEFT JOIN bkcare_users u ON s.id_user = u.id_user
          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
          $where_clause
          ORDER BY s.created_at DESC
          LIMIT $limit OFFSET $offset";

$result = mysqli_query($conn, $query);

// Get kelas for filter
$kelas_filter_query = "SELECT * FROM bkcare_kelas WHERE id_tahun_ajaran = '$tahun_ajaran_id' ORDER BY nama_kelas";
$kelas_filter_result = mysqli_query($conn, $kelas_filter_query);

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 md:items-center md:justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-users text-purple-600 mr-3"></i>
                Data Siswa
            </h1>
            <p class="text-gray-600 text-sm mt-1">Kelola data siswa dan akun mereka</p>
        </div>
        <div class="mt-4 md:mt-0">
            <a href="tambah.php" class="btn-primary px-4 py-2 text-sm inline-flex items-center">
                <i class="fas fa-plus mr-2"></i>
                Tambah Siswa
            </a>
        </div>
    </div>

    <!-- Alert Notifications -->
    <?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 animate-fade-in">
        <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="closeAlert(this)" 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; 
    ?>

    <?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 animate-fade-in">
        <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'] ?? 'Error!' ?></h3>
                <div class="mt-1 text-sm text-red-700"><?= $_SESSION['error_message'] ?></div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="closeAlert(this)" 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; 
    ?>

    <?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 animate-fade-in">
        <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="closeAlert(this)" 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; 
    ?>

    <?php if (isset($_SESSION['info_message'])): ?>
    <div id="info-alert" class="mb-6 rounded-lg p-4 bg-blue-50 border-l-4 border-blue-500 shadow-md animate-fade-in">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <i class="fas fa-info-circle text-blue-500 text-xl"></i>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-medium text-blue-800"><?= $_SESSION['info_title'] ?? 'Informasi' ?></h3>
                <div class="mt-1 text-sm text-blue-700"><?= $_SESSION['info_message'] ?></div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="closeAlert(this)" class="inline-flex text-blue-500 hover:text-blue-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    <?php 
    unset($_SESSION['info_message']);
    unset($_SESSION['info_title']);
    endif; 
    ?>

    <!-- Filter & Search -->
    <div class="card-stat p-4 mb-6">
        <form method="GET" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Search -->
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        <i class="fas fa-search text-purple-600 mr-1"></i>
                        Pencarian
                    </label>
                    <div class="relative">
                        <input type="text" 
                               name="search" 
                               value="<?= htmlspecialchars($search) ?>"
                               placeholder="Cari NIS, Nama, atau Nama Orang Tua..."
                               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 transition">
                        <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                    </div>
                </div>

                <!-- Filter Kelas -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        <i class="fas fa-school text-purple-600 mr-1"></i>
                        Filter Kelas
                    </label>
                    <select name="filter_kelas" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition">
                        <option value="">Semua Kelas</option>
                        <?php while($kelas = mysqli_fetch_assoc($kelas_filter_result)): ?>
                        <option value="<?= $kelas['id_kelas'] ?>" <?= $filter_kelas == $kelas['id_kelas'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($kelas['nama_kelas']) ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Filter Status -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        <i class="fas fa-info-circle text-purple-600 mr-1"></i>
                        Filter Status
                    </label>
                    <select name="filter_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition">
                        <option value="">Semua Status</option>
                        <option value="aktif" <?= $filter_status == 'aktif' ? 'selected' : '' ?>>Aktif</option>
                        <option value="lulus" <?= $filter_status == 'lulus' ? 'selected' : '' ?>>Lulus</option>
                        <option value="pindah" <?= $filter_status == 'pindah' ? 'selected' : '' ?>>Pindah</option>
                    </select>
                </div>
            </div>

            <div class="flex justify-end space-x-2">
                <a href="index.php" class="btn-outline-secondary px-4 py-2 text-sm">
                    <i class="fas fa-redo-alt mr-1"></i>
                    Reset
                </a>
                <button type="submit" class="btn-primary px-4 py-2 text-sm">
                    <i class="fas fa-filter mr-1"></i>
                    Terapkan Filter
                </button>
            </div>
        </form>
    </div>

    <!-- Table -->
    <div class="card-stat overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-hashtag mr-1 text-purple-600"></i>
                            No
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-id-card mr-1 text-purple-600"></i>
                            NIS
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-user mr-1 text-purple-600"></i>
                            Nama
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-venus-mars mr-1 text-purple-600"></i>
                            JK
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-school mr-1 text-purple-600"></i>
                            Kelas
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-phone mr-1 text-purple-600"></i>
                            Kontak
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-info-circle mr-1 text-purple-600"></i>
                            Status
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-user-lock mr-1 text-purple-600"></i>
                            Akun
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <i class="fas fa-cog mr-1 text-purple-600"></i>
                            Aksi
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (mysqli_num_rows($result) > 0): ?>
                        <?php 
                        $no = $offset + 1;
                        while($row = mysqli_fetch_assoc($result)): 
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?= $no++ ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                <span class="bg-purple-100 text-purple-800 px-2 py-1 rounded-lg text-xs">
                                    <?= htmlspecialchars($row['nis']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <div class="flex items-center">
                                    <?php if ($row['jenis_kelamin'] == 'L'): ?>
                                        <i class="fas fa-mars text-blue-500 mr-2"></i>
                                    <?php else: ?>
                                        <i class="fas fa-venus text-pink-500 mr-2"></i>
                                    <?php endif; ?>
                                    <?= htmlspecialchars($row['nama']) ?>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if ($row['jenis_kelamin'] == 'L'): ?>
                                    <span class="badge-info">Laki-laki</span>
                                <?php else: ?>
                                    <span class="badge-warning">Perempuan</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if ($row['nama_kelas']): ?>
                                    <span class="badge-primary">
                                        <i class="fas fa-school mr-1"></i>
                                        <?= htmlspecialchars($row['nama_kelas']) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="badge-secondary">
                                        <i class="fas fa-minus mr-1"></i>
                                        Belum ada kelas
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if ($row['no_hp']): ?>
                                    <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $row['no_hp']) ?>" 
                                       target="_blank" 
                                       class="text-green-600 hover:text-green-700 flex items-center group">
                                        <i class="fab fa-whatsapp mr-1 group-hover:scale-110 transition"></i>
                                        <span class="text-xs"><?= htmlspecialchars($row['no_hp']) ?></span>
                                    </a>
                                <?php else: ?>
                                    <span class="text-gray-400 text-xs">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if ($row['status'] == 'aktif'): ?>
                                    <span class="badge-success">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        Aktif
                                    </span>
                                <?php elseif ($row['status'] == 'lulus'): ?>
                                    <span class="badge-primary">
                                        <i class="fas fa-graduation-cap mr-1"></i>
                                        Lulus
                                    </span>
                                <?php else: ?>
                                    <span class="badge-danger">
                                        <i class="fas fa-exclamation-circle mr-1"></i>
                                        <?= ucfirst($row['status']) ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if ($row['id_user']): ?>
                                    <?php if ($row['user_active'] == 1): ?>
                                        <span class="badge-success flex items-center w-fit" title="Username: <?= $row['username'] ?>">
                                            <i class="fas fa-check-circle mr-1"></i>
                                            Aktif
                                        </span>
                                    <?php else: ?>
                                        <span class="badge-danger flex items-center w-fit">
                                            <i class="fas fa-times-circle mr-1"></i>
                                            Nonaktif
                                        </span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="badge-warning flex items-center w-fit">
                                        <i class="fas fa-exclamation-triangle mr-1"></i>
                                        Belum Ada
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <div class="flex items-center space-x-2">
                                    <a href="detail.php?id=<?= $row['id_siswa'] ?>" 
                                       class="action-btn bg-blue-100 text-blue-600 hover:bg-blue-200"
                                       title="Detail">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit.php?id=<?= $row['id_siswa'] ?>" 
                                       class="action-btn bg-yellow-100 text-yellow-600 hover:bg-yellow-200"
                                       title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button type="button" 
                                            onclick="confirmDelete(<?= $row['id_siswa'] ?>, '<?= htmlspecialchars($row['nama']) ?>')"
                                            class="action-btn bg-red-100 text-red-600 hover:bg-red-200"
                                            title="Hapus">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="px-6 py-12 text-center">
                                <div class="flex flex-col items-center justify-center text-gray-400">
                                    <i class="fas fa-users text-5xl mb-3"></i>
                                    <p class="text-lg font-medium">Tidak ada data siswa</p>
                                    <p class="text-sm">Belum ada data siswa yang tersimpan</p>
                                    <a href="tambah.php" class="btn-primary px-4 py-2 text-sm mt-4">
                                        <i class="fas fa-plus mr-2"></i>
                                        Tambah Siswa
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200">
            <div class="flex items-center justify-between">
                <p class="text-sm text-gray-700">
                    <i class="fas fa-database mr-1 text-purple-600"></i>
                    Total <span class="font-medium"><?= $total_records ?></span> data
                </p>
                <div class="flex items-center space-x-2">
                    <a href="?page=1&search=<?= urlencode($search) ?>&filter_kelas=<?= $filter_kelas ?>&filter_status=<?= $filter_status ?>" 
                       class="pagination-btn <?= $page == 1 ? 'opacity-50 cursor-not-allowed' : '' ?>"
                       <?= $page == 1 ? 'onclick="return false;"' : '' ?>>
                        <i class="fas fa-angle-double-left"></i>
                    </a>
                    <a href="?page=<?= max(1, $page-1) ?>&search=<?= urlencode($search) ?>&filter_kelas=<?= $filter_kelas ?>&filter_status=<?= $filter_status ?>" 
                       class="pagination-btn <?= $page == 1 ? 'opacity-50 cursor-not-allowed' : '' ?>"
                       <?= $page == 1 ? 'onclick="return false;"' : '' ?>>
                        <i class="fas fa-angle-left"></i>
                    </a>
                    
                    <?php
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    for ($i = $start_page; $i <= $end_page; $i++):
                    ?>
                    <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&filter_kelas=<?= $filter_kelas ?>&filter_status=<?= $filter_status ?>" 
                       class="pagination-btn <?= $i == $page ? 'active' : '' ?>">
                        <?= $i ?>
                    </a>
                    <?php endfor; ?>
                    
                    <a href="?page=<?= min($total_pages, $page+1) ?>&search=<?= urlencode($search) ?>&filter_kelas=<?= $filter_kelas ?>&filter_status=<?= $filter_status ?>" 
                       class="pagination-btn <?= $page == $total_pages ? 'opacity-50 cursor-not-allowed' : '' ?>"
                       <?= $page == $total_pages ? 'onclick="return false;"' : '' ?>>
                        <i class="fas fa-angle-right"></i>
                    </a>
                    <a href="?page=<?= $total_pages ?>&search=<?= urlencode($search) ?>&filter_kelas=<?= $filter_kelas ?>&filter_status=<?= $filter_status ?>" 
                       class="pagination-btn <?= $page == $total_pages ? 'opacity-50 cursor-not-allowed' : '' ?>"
                       <?= $page == $total_pages ? 'onclick="return false;"' : '' ?>>
                        <i class="fas fa-angle-double-right"></i>
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<!-- Delete Form (Hidden) -->
<form id="delete-form" method="POST" action="hapus.php" style="display: none;">
    <input type="hidden" name="id_siswa" id="delete-id">
</form>

<style>
/* Custom animations */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

.animate-fade-in {
    animation: fadeIn 0.3s ease-out;
}

/* Action buttons */
.action-btn {
    @apply w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200;
}

.action-btn:hover {
    @apply transform scale-110;
}

/* Pagination */
.pagination-btn {
    @apply w-8 h-8 flex items-center justify-center rounded-lg text-sm font-medium transition-all duration-200;
}

.pagination-btn:not(.active):not([onclick="return false;"]) {
    @apply bg-white text-gray-700 border border-gray-300 hover:bg-purple-50 hover:text-purple-600 hover:border-purple-300;
}

.pagination-btn.active {
    @apply bg-purple-600 text-white;
}

.pagination-btn[onclick="return false;"] {
    @apply bg-gray-100 text-gray-400 cursor-not-allowed;
}
</style>

<script>
function closeAlert(element) {
    element.closest('[id$="-alert"]').remove();
}

function confirmDelete(id, nama) {
    if (confirm('Apakah Anda yakin ingin menghapus siswa "' + nama + '"?\nData yang terkait dengan siswa ini juga akan ikut terhapus!')) {
        document.getElementById('delete-id').value = id;
        document.getElementById('delete-form').submit();
    }
}

// Auto hide alerts after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('[id$="-alert"]');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    if (alert) alert.remove();
                }, 500);
            }
        }, 5000);
    });
});
</script>

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