<?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 untuk menampilkan data kelas
$query = "SELECT k.*, g.nama_guru as nama_wali, u.username as username_wali, u.role as role_wali,
          ta.tahun_ajaran as ta_tahun, ta.semester as ta_semester,
          (SELECT COUNT(*) FROM bkcare_siswa_kelas sk 
           WHERE sk.id_kelas = k.id_kelas AND sk.status = 'aktif') as jumlah_siswa
          FROM bkcare_kelas k
          LEFT JOIN bkcare_guru g ON k.wali_kelas = g.id_guru
          LEFT JOIN bkcare_users u ON g.id_user = u.id_user
          LEFT JOIN bkcare_tahun_ajaran ta ON k.id_tahun_ajaran = ta.id_tahun_ajaran
          ORDER BY 
          CASE WHEN ta.status = 'aktif' THEN 0 ELSE 1 END,
          k.nama_kelas ASC";
$result = mysqli_query($conn, $query);

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

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-school text-purple-600 mr-3"></i>
                Data Kelas
            </h1>
            <p class="text-gray-600 text-sm mt-1">Kelola data kelas dan wali kelas</p>
        </div>
        <a href="tambah.php" class="btn-primary">
            <i class="fas fa-plus mr-2"></i>Tambah Kelas
        </a>
    </div>

    <!-- Info Tahun Ajaran Aktif -->
    <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg">
        <div class="flex items-center">
            <i class="fas fa-info-circle text-blue-500 mr-3 text-xl"></i>
            <div>
                <p class="text-blue-700 font-medium">Tahun Ajaran Aktif: 
                    <strong><?= $tahun_ajaran ? htmlspecialchars($tahun_ajaran['tahun_ajaran']) . ' - Semester ' . ucfirst($tahun_ajaran['semester']) : 'Belum ada tahun ajaran aktif' ?></strong>
                </p>
                <p class="text-blue-600 text-sm mt-1">Data kelas ditampilkan berdasarkan tahun ajaran aktif</p>
            </div>
        </div>
    </div>

    <!-- Success Alert dari session -->
    <?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 dari session -->
    <?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 dari session -->
    <?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; 
    ?>

    <!-- Table -->
    <div class="card-stat p-6">
        <div class="overflow-x-auto">
            <table class="w-full">
                <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">Nama Kelas</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Wali Kelas</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jml Siswa</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tahun Ajaran</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">
                                <td class="px-6 py-4 text-sm text-gray-600"><?= $no++ ?></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-school text-purple-600 text-sm"></i>
                                        </div>
                                        <?= htmlspecialchars($row['nama_kelas']) ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['nama_wali']): ?>
                                        <div class="flex flex-col">
                                            <span class="font-medium text-gray-800"><?= htmlspecialchars($row['nama_wali']) ?></span>
                                            <span class="text-xs text-gray-500">
                                                <i class="fas fa-tag mr-1"></i>
                                                <?= ucfirst(str_replace('_', ' ', $row['role_wali'] ?? '')) ?>
                                                (<?= htmlspecialchars($row['username_wali'] ?? '') ?>)
                                            </span>
                                        </div>
                                    <?php else: ?>
                                        <span class="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-exclamation-triangle mr-1"></i>
                                            Belum Ada Wali Kelas
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <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-users mr-1"></i>
                                        <?= $row['jumlah_siswa'] ?> Siswa
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['id_tahun_ajaran'] == $tahun_ajaran_id): ?>
                                        <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-check-circle mr-1"></i>Aktif
                                        </span>
                                    <?php else: ?>
                                        <span class="text-gray-500">
                                            <?= htmlspecialchars($row['ta_tahun'] ?? '-') ?> 
                                            <?= $row['ta_semester'] ? '(' . ucfirst($row['ta_semester']) . ')' : '' ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-right">
                                    <a href="edit.php?id=<?= $row['id_kelas'] ?>" 
                                       class="text-blue-600 hover:text-blue-800 mx-2"
                                       data-bs-toggle="tooltip" 
                                       title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if ($row['jumlah_siswa'] > 0): ?>
                                        <span class="text-gray-400 mx-2 cursor-not-allowed" 
                                              data-bs-toggle="tooltip" 
                                              title="Tidak dapat dihapus karena masih memiliki <?= $row['jumlah_siswa'] ?> siswa">
                                            <i class="fas fa-trash"></i>
                                        </span>
                                    <?php else: ?>
                                        <a href="#" 
                                           onclick="confirmDelete(<?= $row['id_kelas'] ?>, '<?= htmlspecialchars($row['nama_kelas']) ?>')"
                                           class="text-red-600 hover:text-red-800 mx-2"
                                           data-bs-toggle="tooltip" 
                                           title="Hapus Data">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-school text-5xl mb-3 text-gray-300"></i>
                                <p class="text-lg font-medium">Belum ada data kelas</p>
                                <p class="text-sm mt-1">Klik tombol "Tambah Kelas" untuk menambahkan data</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Modal Konfirmasi Hapus -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-2xl">
            <div class="modal-header bg-red-500 text-white rounded-t-2xl">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Konfirmasi Hapus
                </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">Apakah Anda yakin ingin menghapus data kelas:</p>
                <p class="font-semibold text-gray-800" id="deleteItemInfo"></p>
                <p class="text-sm text-red-600 mt-3">
                    <i class="fas fa-info-circle mr-1"></i>
                    Data yang sudah dihapus tidak dapat dikembalikan!
                </p>
            </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="confirmDeleteBtn" class="bg-red-500 text-white px-6 py-2 rounded-full hover:bg-red-600 transition text-sm">
                    <i class="fas fa-trash mr-1"></i>Ya, Hapus
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Fungsi konfirmasi hapus
function confirmDelete(id, info) {
    document.getElementById('deleteItemInfo').textContent = info;
    document.getElementById('confirmDeleteBtn').href = 'hapus.php?id=' + id;
    var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}

// Tooltip initialization
$(document).ready(function() {
    // Auto hide alerts after 5 seconds
    setTimeout(function() {
        $('#success-alert, #error-alert, #warning-alert').fadeOut('slow');
    }, 5000);
    
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

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