<?php
require_once '../includes/header.php';
require_once '../includes/navbar.php';

// Inisialisasi variabel
$tahun_aktif = null;
$id_tahun_aktif = null;

// Konfigurasi pagination
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Validasi limit
$allowed_limits = [10, 30, 50, 100, 999999];
if (!in_array($limit, $allowed_limits)) {
    $limit = 10;
}

// Validasi page
if ($page < 1) {
    $page = 1;
}

// Hitung offset
$offset = ($page - 1) * $limit;

// Query untuk mendapatkan tahun ajaran yang aktif
$query_tahun_aktif = "SELECT id_tahunajaran, tahun_ajaran FROM bind_tahunajaran WHERE aktif = 1";
$result_tahun_aktif = mysqli_query($conn, $query_tahun_aktif);

// Build query dasar dengan JOIN ke bind_datasiswa
$query_base = "SELECT s.*, t.tahun_ajaran, t.aktif, ds.status as status_siswa
              FROM bind_siswa s 
              JOIN bind_datasiswa ds ON s.id_siswa = ds.id_siswa
              JOIN bind_tahunajaran t ON ds.id_tahunajaran = t.id_tahunajaran";

$query_where = "";
$query_params = [];

if ($result_tahun_aktif && mysqli_num_rows($result_tahun_aktif) > 0) {
    $tahun_aktif = mysqli_fetch_assoc($result_tahun_aktif);
    $id_tahun_aktif = $tahun_aktif['id_tahunajaran'];
    $query_where = " WHERE ds.id_tahunajaran = '$id_tahun_aktif'";
} 

// Tambahkan kondisi pencarian jika ada
if (!empty($search)) {
    if (empty($query_where)) {
        $query_where = " WHERE (s.nisn LIKE '%$search%' OR s.nis LIKE '%$search%' OR s.nama_lengkap LIKE '%$search%')";
    } else {
        $query_where .= " AND (s.nisn LIKE '%$search%' OR s.nis LIKE '%$search%' OR s.nama_lengkap LIKE '%$search%')";
    }
}

// Query untuk data dengan limit
$query = $query_base . $query_where . " ORDER BY s.id_siswa DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

// Query untuk total data
$query_total = "SELECT COUNT(*) as total 
                FROM bind_siswa s 
                JOIN bind_datasiswa ds ON s.id_siswa = ds.id_siswa
                JOIN bind_tahunajaran t ON ds.id_tahunajaran = t.id_tahunajaran" . $query_where;
$result_total = mysqli_query($conn, $query_total);
$total_data = mysqli_fetch_assoc($result_total)['total'];

// Hitung total halaman
$total_pages = ceil($total_data / $limit);

// Pastikan page tidak melebihi total halaman
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
    // Redirect ke halaman yang benar
    $params = $_GET;
    $params['page'] = $page;
    header('Location: index.php?' . http_build_query($params));
    exit;
}
?>


<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Daftar Siswa</h2>
        <div>
            <a href="tambah.php" class="btn btn-primary">
                <i class="fas fa-user-plus me-1"></i> Tambah Siswa
            </a>
            <a href="import.php" class="btn btn-info">
                <i class="fas fa-file-import me-1"></i> Import Excel
            </a>
            <a href="#" target="_blank" class="btn btn-success">
                <i class="fas fa-file-pdf me-1"></i> Cetak PDF
            </a>
        </div>
    </div>

    <?php if ($tahun_aktif): ?>
    <div class="alert alert-info">
        Menampilkan data siswa untuk tahun ajaran aktif: <strong><?php echo htmlspecialchars($tahun_aktif['tahun_ajaran']); ?></strong>
    </div>
    <?php else: ?>
    <div class="alert alert-warning">
        <strong>Perhatian!</strong> Tidak ada tahun ajaran yang aktif. Menampilkan semua data siswa.
    </div>
    <?php endif; ?>

    <!-- Card Pencarian dan Informasi -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <form method="GET" class="d-flex">
                        <input type="text" name="search" class="form-control me-2" placeholder="Cari NISN, NIS atau Nama Siswa..." value="<?php echo htmlspecialchars($search); ?>">
                        <button type="submit" class="btn btn-primary">Cari</button>
                        <?php if (!empty($search)): ?>
                            <a href="index.php" class="btn btn-secondary ms-2">Reset</a>
                        <?php endif; ?>
                    </form>
                </div>
                <div class="col-md-6 d-flex justify-content-end align-items-center">
                    <span class="me-2">Tampilkan:</span>
                    <select class="form-select form-select-sm w-auto" id="limitSelector">
                        <option value="10" <?php echo $limit == 10 ? 'selected' : ''; ?>>10</option>
                        <option value="30" <?php echo $limit == 30 ? 'selected' : ''; ?>>30</option>
                        <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50</option>
                        <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100</option>
                        <option value="999999" <?php echo $limit == 999999 ? 'selected' : ''; ?>>Semua</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Informasi Jumlah Data -->
        <div class="alert alert-light d-flex justify-content-between align-items-center">
            <div>
                Menampilkan <strong><?php echo ($result && mysqli_num_rows($result) > 0) ? (($page - 1) * $limit + 1) : 0; ?></strong> 
                sampai <strong><?php echo ($result && mysqli_num_rows($result) > 0) ? min($page * $limit, $total_data) : 0; ?></strong> 
                dari <strong><?php echo $total_data; ?></strong> data
            </div>
            <?php if (!empty($search)): ?>
                <div>
                    Hasil pencarian untuk: <strong>"<?php echo htmlspecialchars($search); ?>"</strong>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover" id="tabelSiswa">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>NISN</th>
                            <th>NIS</th>
                            <th>Nama Lengkap</th>
                            <th>Jenis Kelamin</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($result && mysqli_num_rows($result) > 0) {
                            $no = ($page - 1) * $limit + 1;
                            while ($row = mysqli_fetch_assoc($result)) {
                                $jenis_kelamin = $row['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan';
                                
                                // Tampilkan status siswa dari bind_datasiswa
                                $status_siswa = $row['status_siswa'];
                                $status_badge = '';
                                
                                switch ($status_siswa) {
                                    case 'Aktif':
                                        $status_badge = '<span class="badge bg-success">Aktif</span>';
                                        break;
                                    case 'Lulus':
                                        $status_badge = '<span class="badge bg-primary">Lulus</span>';
                                        break;
                                    case 'Keluar':
                                        $status_badge = '<span class="badge bg-warning">Keluar</span>';
                                        break;
                                    case 'Mutasi':
                                        $status_badge = '<span class="badge bg-info">Mutasi</span>';
                                        break;
                                    default:
                                        $status_badge = '<span class="badge bg-secondary">' . $status_siswa . '</span>';
                                        break;
                                }
                                
                                echo "<tr>
                                    <td>{$no}</td>
                                    <td>" . htmlspecialchars($row['nisn']) . "</td>
                                    <td>" . htmlspecialchars($row['nis']) . "</td>
                                    <td>" . htmlspecialchars($row['nama_lengkap']) . "</td>
                                    <td>{$jenis_kelamin}</td>
                                    <td>{$status_badge}</td>
                                    <td>
                                        <a href='detail.php?id={$row['id_siswa']}' class='btn btn-sm btn-info me-1' title='Detail'>
                                            <i class='bi bi-eye'></i>
                                        </a>

                                        <a href='edit.php?id={$row['id_siswa']}' class='btn btn-sm btn-warning me-1' title='Edit'>
                                            <i class='bi bi-pencil-square'></i>
                                        </a>

                                        <a href='cetak.php?id={$row['id_siswa']}' target='_blank' class='btn btn-sm btn-secondary me-1' title='Cetak PDF'>
                                            <i class='bi bi-file-earmark-pdf'></i>
                                        </a>

                                        <button class='btn btn-sm btn-danger btn-hapus' 
                                                data-id='{$row['id_siswa']}'
                                                data-nama=\"" . htmlspecialchars($row['nama_lengkap']) . "\" 
                                                title='Hapus'>
                                            <i class='bi bi-trash'></i>
                                        </button>
                                    </td>
                                </tr>";
                                $no++;
                            }
                        } else {
                            echo "<tr>
                                <td colspan='7' class='text-center'>
                                    <div class='alert alert-info text-center py-4 mb-0'>
                                        <i class='fas fa-info-circle fa-2x mb-3'></i>
                                        <h5>Belum ada data siswa</h5>
                                        <p class='mb-0'>Silakan tambah data siswa melalui tombol Tambah Siswa atau Import Excel diatas</p>
                                    </div>
                                </td>
                            </tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <!-- Previous Page Link -->
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>

                    <!-- Page Numbers -->
                    <?php
                    // Tentukan range halaman yang akan ditampilkan
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    // Jika di awal, tampilkan lebih banyak di akhir
                    if ($page <= 3) {
                        $end_page = min($total_pages, 5);
                    }
                    
                    // Jika di akhir, tampilkan lebih banyak di awal
                    if ($page >= $total_pages - 2) {
                        $start_page = max(1, $total_pages - 4);
                    }
                    
                    // Tampilkan halaman pertama jika tidak termasuk dalam range
                    if ($start_page > 1) {
                        echo '<li class="page-item"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => 1])) . '">1</a></li>';
                        if ($start_page > 2) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                    }
                    
                    // Tampilkan halaman dalam range
                    for ($i = $start_page; $i <= $end_page; $i++) {
                        $active = $i == $page ? 'active' : '';
                        echo '<li class="page-item ' . $active . '"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => $i])) . '">' . $i . '</a></li>';
                    }
                    
                    // Tampilkan halaman terakhir jika tidak termasuk dalam range
                    if ($end_page < $total_pages) {
                        if ($end_page < $total_pages - 1) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                        echo '<li class="page-item"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => $total_pages])) . '">' . $total_pages . '</a></li>';
                    }
                    ?>

                    <!-- Next Page Link -->
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnHapus = document.querySelectorAll('.btn-hapus');
    
    btnHapus.forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const nama = this.getAttribute('data-nama');
            
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: `Data siswa ${nama} akan dihapus permanen!`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `hapus.php?id=${id}`;
                }
            });
        });
    });

    // Limit selector change handler
    const limitSelector = document.getElementById('limitSelector');
    if (limitSelector) {
        limitSelector.addEventListener('change', function() {
            const url = new URL(window.location.href);
            url.searchParams.set('limit', this.value);
            url.searchParams.set('page', 1); // Reset to first page when changing limit
            window.location.href = url.toString();
        });
    }
});
</script>

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