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

if (!isset($_SESSION['login'])) {
    // Tampilkan hanya konten umum untuk pengunjung tanpa login
    echo '<div class="container mt-4">';
    echo '  <div class="jumbotron bg-light p-5 rounded">';
    echo '    <h1 class="display-4">Selamat Datang di Buku Induk Sekolah</h1>';
    echo '    <h3>SMAN 1 BANTARAN (SMANSAB)</h3>';
    echo '    <p class="lead">Sistem manajemen data siswa yang lengkap dan terintegrasi.</p>';
    echo '    <hr class="my-4">';
    echo '    <p>Silakan login untuk mengakses sistem.</p>';
    echo '    <a class="btn btn-primary btn-lg" href="../login.php" role="button">Login</a>';
    echo '  </div>';
    echo '</div>';
    require_once 'includes/footer.php';
    exit;
}

// Ambil tahun ajaran aktif
$query_tahun_aktif = "SELECT * FROM bind_tahunajaran WHERE aktif = 1 LIMIT 1";
$result_tahun_aktif = mysqli_query($conn, $query_tahun_aktif);
$tahun_aktif = mysqli_fetch_assoc($result_tahun_aktif);

if (!$tahun_aktif) {
    echo '<div class="container mt-4">';
    echo '  <div class="alert alert-danger">Tidak ada tahun ajaran yang aktif. Silakan hubungi administrator.</div>';
    echo '</div>';
    require_once '../includes/footer.php';
    exit;
}

// 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']) : '';
$jenis_gtk_filter = isset($_GET['jenis_gtk']) ? mysqli_real_escape_string($conn, $_GET['jenis_gtk']) : '';
$tahun_ajaran_filter = isset($_GET['tahun_ajaran']) ? (int)$_GET['tahun_ajaran'] : $tahun_aktif['id_tahunajaran'];

// 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 semua jenis GTK yang tersedia (untuk dropdown filter)
$query_jenis_gtk = "SELECT DISTINCT jenis_gtk FROM bind_gtk WHERE jenis_gtk IS NOT NULL AND jenis_gtk != '' ORDER BY jenis_gtk";
$result_jenis_gtk = mysqli_query($conn, $query_jenis_gtk);
$jenis_gtk_options = [];
while ($row = mysqli_fetch_assoc($result_jenis_gtk)) {
    $jenis_gtk_options[] = $row['jenis_gtk'];
}

// Query untuk mendapatkan semua tahun ajaran (untuk dropdown filter)
$query_tahun_ajaran = "SELECT * FROM bind_tahunajaran ORDER BY tahun_ajaran DESC";
$result_tahun_ajaran = mysqli_query($conn, $query_tahun_ajaran);
$tahun_ajaran_options = [];
while ($row = mysqli_fetch_assoc($result_tahun_ajaran)) {
    $tahun_ajaran_options[$row['id_tahunajaran']] = $row['tahun_ajaran'];
}

// Build query dasar
$query_base = "SELECT g.*, t.tahun_ajaran 
               FROM bind_gtk g 
               LEFT JOIN bind_tahunajaran t ON g.id_tahunajaran = t.id_tahunajaran";
$query_where = "";
$query_params = [];

// Tambahkan kondisi pencarian jika ada
if (!empty($search)) {
    $query_where .= (empty($query_where) ? " WHERE " : " AND ") . " (g.nip LIKE '%$search%' OR g.nuptk LIKE '%$search%' OR g.nama LIKE '%$search%')";
}

// Tambahkan filter jenis GTK jika dipilih
if (!empty($jenis_gtk_filter)) {
    $query_where .= (empty($query_where) ? " WHERE " : " AND ") . " g.jenis_gtk = '$jenis_gtk_filter'";
}

// Tambahkan filter tahun ajaran
if (!empty($tahun_ajaran_filter)) {
    $query_where .= (empty($query_where) ? " WHERE " : " AND ") . " g.id_tahunajaran = $tahun_ajaran_filter";
} else {
    $query_where .= (empty($query_where) ? " WHERE " : " AND ") . " g.id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
}

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

// Query untuk total data
$query_total = "SELECT COUNT(*) as total FROM bind_gtk g" . $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">
        <div>
            <h2>Daftar Guru & Tenaga Kependidikan</h2>
            <p class="text-muted mb-0">
                Tahun Ajaran: <strong><?php echo $tahun_aktif['tahun_ajaran']; ?></strong>
                <?php echo $tahun_ajaran_filter != $tahun_aktif['id_tahunajaran'] ? 
                    ' (Filter: ' . $tahun_ajaran_options[$tahun_ajaran_filter] . ')' : ''; ?>
            </p>
        </div>
        <div>
            <a href="tambah.php" class="btn btn-primary">
                <i class="fas fa-user-plus me-1"></i> Tambah GTK
            </a>
            <a href="import.php" class="btn btn-info">
                <i class="fas fa-file-import me-1"></i> Import
            </a>
            <a href="cetak.php" target="_blank" class="btn btn-success">
                <i class="fas fa-file-pdf me-1"></i> Cetak PDF
            </a>
        </div>
    </div>

    <!-- Card Pencarian dan Informasi -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET">
                <div class="row">
                    <div class="col-md-4 mb-2 mb-md-0">
                        <div class="input-group">
                            <input type="text" name="search" class="form-control" placeholder="Cari NIP, NUPTK atau Nama..." value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit" class="btn btn-primary">Cari</button>
                            <?php if (!empty($search) || !empty($jenis_gtk_filter) || $tahun_ajaran_filter != $tahun_aktif['id_tahunajaran']): ?>
                                <a href="index.php" class="btn btn-secondary ms-2">Reset</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="col-md-3 mb-2 mb-md-0">
                        <select name="jenis_gtk" class="form-select">
                            <option value="">Semua Jenis GTK</option>
                            <?php foreach ($jenis_gtk_options as $option): ?>
                                <option value="<?php echo htmlspecialchars($option); ?>" <?php echo $jenis_gtk_filter == $option ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                   <!-- <div class="col-md-3 mb-2 mb-md-0">
                        <select name="tahun_ajaran" class="form-select">
                            <option value="<?php echo $tahun_aktif['id_tahunajaran']; ?>">Tahun Ajaran Aktif (<?php echo $tahun_aktif['tahun_ajaran']; ?>)</option>
                            <?php foreach ($tahun_ajaran_options as $id => $tahun): ?>
                                <?php if ($id != $tahun_aktif['id_tahunajaran']): ?>
                                    <option value="<?php echo $id; ?>" <?php echo $tahun_ajaran_filter == $id ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($tahun); ?>
                                    </option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div> -->
                    <div class="col-md-2 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" name="limit">
                            <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>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover" id="tabelGuru">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>NIP</th>
                            <th>NUPTK</th>
                            <th>Nama</th>
                            <th>Jenis GTK</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)) {
                                $status_badge = $row['status_aktif'] == 1 ? 
                                    '<span class="badge bg-success">Aktif</span>' : 
                                    '<span class="badge bg-secondary">Non-Aktif</span>';
                                
                               echo "<tr>
        <td>{$no}</td>
        <td>" . htmlspecialchars($row['nip'] ?? '-') . "</td>
        <td>" . htmlspecialchars($row['nuptk'] ?? '-') . "</td>
        <td>" . htmlspecialchars($row['nama']) . "</td>
        <td>" . htmlspecialchars($row['jenis_gtk']) . "</td>
        <td>{$status_badge}</td>
        <td>
            <a href='detail.php?id={$row['id_gtk']}' class='btn btn-sm btn-info me-1' title='Detail'>
                <i class='bi bi-eye'></i>
            </a>
            <a href='edit.php?id={$row['id_gtk']}' class='btn btn-sm btn-warning me-1' title='Edit'>
                <i class='bi bi-pencil-square'></i>
            </a>
            <button class='btn btn-sm btn-danger btn-hapus' 
                    data-id='{$row['id_gtk']}' 
                    data-nama=\"" . htmlspecialchars($row['nama']) . "\" 
                    title='Hapus'>
                <i class='bi bi-trash'></i>
            </button>
        </td>
    </tr>";

                                $no++;
                            }
                        } else {
                            echo "<tr>
                                <td colspan='8' 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 GTK</h5>
                                        <p class='mb-0'>Silakan tambah data GTK melalui tombol Tambah GTK diatas</p>
                                    </div>
                                </td>
                            </tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </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) || !empty($jenis_gtk_filter) || $tahun_ajaran_filter != $tahun_aktif['id_tahunajaran']): ?>
                    <div>
                        <?php if (!empty($search)): ?>
                            Hasil pencarian untuk: <strong>"<?php echo htmlspecialchars($search); ?>"</strong>
                        <?php endif; ?>
                        <?php if (!empty($search) && (!empty($jenis_gtk_filter) || $tahun_ajaran_filter != $tahun_aktif['id_tahunajaran'])): ?> | <?php endif; ?>
                        <?php if (!empty($jenis_gtk_filter)): ?>
                            Filter: <strong><?php echo htmlspecialchars($jenis_gtk_filter); ?></strong>
                        <?php endif; ?>
                        <?php if (!empty($jenis_gtk_filter) && $tahun_ajaran_filter != $tahun_aktif['id_tahunajaran']): ?> | <?php endif; ?>
                        <?php if ($tahun_ajaran_filter != $tahun_aktif['id_tahunajaran']): ?>
                            Tahun Ajaran: <strong><?php echo htmlspecialchars($tahun_ajaran_options[$tahun_ajaran_filter]); ?></strong>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination (tetap sama seperti sebelumnya) -->
            <?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 GTK ${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() {
            this.form.submit();
        });
    }
    
    // Jenis GTK filter change handler
    const jenisGtkFilter = document.querySelector('select[name="jenis_gtk"]');
    if (jenisGtkFilter) {
        jenisGtkFilter.addEventListener('change', function() {
            this.form.submit();
        });
    }
    
    // Tahun ajaran filter change handler
    const tahunAjaranFilter = document.querySelector('select[name="tahun_ajaran"]');
    if (tahunAjaranFilter) {
        tahunAjaranFilter.addEventListener('change', function() {
            this.form.submit();
        });
    }
});
</script>

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