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

// Koneksi database
//require_once 'config/database.php';

// Pastikan session dimulai
//require_once 'includes/header.php';

// Jika tidak login, redirect sudah ditangani oleh header.php
// Jadi kita hanya perlu memastikan pengguna sudah login di sini
if (!isset($_SESSION['login'])) {
    exit(); // Header sudah melakukan redirect
}

// Tampilkan alert login sukses jika ada
if (isset($_SESSION['show_login_alert']) && $_SESSION['show_login_alert'] === true) {
    $alert_data = $_SESSION['login_alert_data'];
    echo "<script>
        Swal.fire({
            icon: '{$alert_data['icon']}',
            title: '{$alert_data['title']}',
            text: '{$alert_data['text']}',
            timer: {$alert_data['timer']},
            showConfirmButton: false
        });
    </script>";
    
    // Hapus session alert setelah ditampilkan
    unset($_SESSION['show_login_alert']);
    unset($_SESSION['login_alert_data']);
}

// Query untuk mendapatkan tahun ajaran aktif
$query_tahun_aktif = "SELECT * FROM bind_tahunajaran WHERE aktif = TRUE 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'>
        <div class='alert alert-warning'>
            <i class='fas fa-exclamation-triangle me-2'></i>Tidak ada tahun ajaran yang aktif.
        </div>
    </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']) : '';

// 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 total siswa pada tahun ajaran aktif dengan pencarian
$query_total = "SELECT COUNT(*) as total 
                FROM bind_datasiswa ds 
                JOIN bind_siswa s ON ds.id_siswa = s.id_siswa 
                WHERE ds.id_tahunajaran = " . $tahun_aktif['id_tahunajaran'];
$query_total_search = "";

if (!empty($search)) {
    $query_total_search = " AND (s.nisn LIKE '%$search%' OR s.nis LIKE '%$search%' OR s.nama_lengkap LIKE '%$search%')";
    $query_total .= $query_total_search;
}

$result_total = mysqli_query($conn, $query_total);
$total_siswa = mysqli_fetch_assoc($result_total)['total'];

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

// Pastikan page tidak melebihi total halaman
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
}

// Query untuk mendapatkan data siswa dengan pagination dan pencarian
$query_siswa = "SELECT s.* 
                FROM bind_datasiswa ds 
                JOIN bind_siswa s ON ds.id_siswa = s.id_siswa 
                WHERE ds.id_tahunajaran = " . $tahun_aktif['id_tahunajaran'];

if (!empty($search)) {
    $query_siswa .= " AND (s.nisn LIKE '%$search%' OR s.nis LIKE '%$search%' OR s.nama_lengkap LIKE '%$search%')";
}

$query_siswa .= " ORDER BY s.nama_lengkap LIMIT $limit OFFSET $offset";
$result_siswa = mysqli_query($conn, $query_siswa);

// Fungsi untuk memeriksa kelengkapan data per siswa
function check_student_completion($conn, $student_id) {
    $tables = array(
        'bind_pendidikan_siswa' => 'Data Pendidikan',
        'bind_orang_tua' => 'Data Orang Tua',
        'bind_siswa_kegemaran' => 'Data Kegemaran',
        'bind_prestasi_siswa' => 'Data Prestasi',
        'bind_beasiswa_siswa' => 'Data Beasiswa',
        'bind_perkembangan_siswa' => 'Data Perkembangan'
    );
    
    $completed = 0;
    $total = count($tables);
    
    foreach ($tables as $table => $name) {
        $query = "SELECT COUNT(*) as count FROM $table WHERE id_siswa = $student_id";
        $result = mysqli_query($conn, $query);
        $data = mysqli_fetch_assoc($result);
        
        if ($data['count'] > 0) {
            $completed++;
        }
    }
    
    // Data bind_siswa selalu dianggap lengkap
    $completed++;
    $total++;
    
    return array(
        'completed' => $completed,
        'total' => $total,
        'percentage' => round(($completed / $total) * 100)
    );
}

?>

<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="jumbotron bg-light p-5 rounded">
                <h1 class="display-4">Selamat Datang di Buku Induk Sekolah</h1>
                <h3>SMAN 1 BANTARAN (SMANSAB)</h3>
                <p class="lead">Sistem manajemen data siswa yang lengkap dan terintegrasi.</p>
                <hr class="my-4">
                <p>Kelola data siswa, orang tua, prestasi, beasiswa, dan perkembangan akademik dengan mudah.</p>
                <a class="btn btn-primary btn-lg" href="siswa/index.php" role="button"> Lihat Data </a>
            </div>
        </div>
    </div>

    

    <!-- Progress Kelengkapan Data per Siswa -->
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-tasks me-2"></i>Kelengkapan Data per Siswa
                    </h5>
                    <div class="d-flex align-items-center">
                        <form method="GET" class="d-flex me-3">
                            <input type="text" name="search" class="form-control form-control-sm me-2" placeholder="Cari NISN, NIS atau Nama..." value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit" class="btn btn-light btn-sm">Cari</button>
                            <?php if (!empty($search)): ?>
                                <a href="index.php" class="btn btn-outline-light btn-sm ms-2">Reset</a>
                            <?php endif; ?>
                        </form>
                        <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 class="card-body">
                    <!-- Informasi Jumlah Data -->
                    <div class="alert alert-light d-flex justify-content-between align-items-center mb-3">
                        <div>
                            Menampilkan <strong><?php echo ($result_siswa && mysqli_num_rows($result_siswa) > 0) ? (($page - 1) * $limit + 1) : 0; ?></strong> 
                            sampai <strong><?php echo ($result_siswa && mysqli_num_rows($result_siswa) > 0) ? min($page * $limit, $total_siswa) : 0; ?></strong> 
                            dari <strong><?php echo $total_siswa; ?></strong> data
                        </div>
                        <?php if (!empty($search)): ?>
                            <div>
                                Hasil pencarian untuk: <strong>"<?php echo htmlspecialchars($search); ?>"</strong>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-striped table-bordered table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th width="50">No.</th>
                                    <th>NISN</th>
                                    <th>NIS</th>
                                    <th>Nama Lengkap</th>
                                    <th>Jenis Kelamin</th>
                                    <th width="250">Progress Kelengkapan</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $no = ($page - 1) * $limit + 1;
                                if (mysqli_num_rows($result_siswa) > 0) {
                                    while ($siswa = mysqli_fetch_assoc($result_siswa)) {
                                        $completion = check_student_completion($conn, $siswa['id_siswa']);
                                        $progress_color = '';
                                        if ($completion['percentage'] < 50) {
                                            $progress_color = 'bg-danger';
                                        } elseif ($completion['percentage'] < 80) {
                                            $progress_color = 'bg-warning';
                                        } else {
                                            $progress_color = 'bg-success';
                                        }
                                ?>
                                <tr>
                                    <td class="text-center"><?php echo $no++; ?></td>
                                    <td><?php echo htmlspecialchars($siswa['nisn']); ?></td>
                                    <td><?php echo htmlspecialchars($siswa['nis']); ?></td>
                                    <td><?php echo htmlspecialchars($siswa['nama_lengkap']); ?></td>
                                    <td><?php echo $siswa['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan'; ?></td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="progress flex-grow-1 me-2" style="height: 20px;">
                                                <div class="progress-bar <?php echo $progress_color; ?>" 
                                                    role="progressbar" 
                                                    style="width: <?php echo $completion['percentage']; ?>%;" 
                                                    aria-valuenow="<?php echo $completion['percentage']; ?>" 
                                                    aria-valuemin="0" 
                                                    aria-valuemax="100">
                                                    <?php echo $completion['percentage']; ?>%
                                                </div>
                                            </div>
                                            <small class="text-muted"><?php echo $completion['completed']; ?>/<?php echo $completion['total']; ?></small>
                                        </div>
                                    </td>
                                </tr>
                                <?php 
                                    }
                                } else {
                                    echo '<tr><td colspan="6" class="text-center">Tidak ada data siswa</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>
    </div>
</div>

<div class="row mt-4">
        <div class="col-md-3 mb-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title">Siswa</h5>
                    <p class="card-text">Kelola data siswa</p>
                    <a href="siswa/index.php" class="btn btn-outline-primary">Lihat Data</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title">Orang Tua</h5>
                    <p class="card-text">Data orang tua/wali</p>
                    <a href="orangtua/" class="btn btn-outline-primary">Lihat Data</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title">Prestasi</h5>
                    <p class="card-text">Pencapaian siswa</p>
                    <a href="prestasi/" class="btn btn-outline-primary">Lihat Data</a>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title">Beasiswa</h5>
                    <p class="card-text">Program beasiswa</p>
                    <a href="beasiswa/" class="btn btn-outline-primary">Lihat Data</a>
                </div>
            </div>
        </div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 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';
?>