<?php $__env->startSection('title', 'Manajemen Data Siswa'); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
    <div class="col-12">

        <!-- Filter & Search -->
        <div class="card card-outline card-primary">
            <div class="card-header">
                <h3 class="card-title">Filter Pencarian</h3>
            </div>
            <div class="card-body">
                <form action="<?php echo e(route('siswa.index')); ?>" method="GET">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <input type="text" name="search" class="form-control" placeholder="Cari Nama, NIS, WA, Kelas..." value="<?php echo e(request('search')); ?>">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <select name="status" class="form-control">
                                    <option value="">Semua Status (Aktif/Tidak/Lulus)</option>
                                    <option value="aktif" <?php echo e(request('status') == 'aktif' ? 'selected' : ''); ?>>Aktif</option>
                                    <option value="tidak_aktif" <?php echo e(request('status') == 'tidak_aktif' ? 'selected' : ''); ?>>Non Aktif</option>
                                    <option value="lulus" <?php echo e(request('status') == 'lulus' ? 'selected' : ''); ?>>Lulus</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <select name="kategori" class="form-control">
                                    <option value="">Semua Kategori</option>
                                    <option value="internal" <?php echo e(request('kategori') == 'internal' ? 'selected' : ''); ?>>Internal</option>
                                    <option value="external" <?php echo e(request('kategori') == 'external' ? 'selected' : ''); ?>>External</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <select name="tahun_ajaran_id" class="form-control select2-ajax-ta" data-placeholder="Semua Tahun Ajaran">
                                    <option value="">Semua Tahun Ajaran</option>
                                    <?php if($selectedTa): ?>
                                        <option value="<?php echo e($selectedTa->id); ?>" selected><?php echo e($selectedTa->tahun); ?></option>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <select name="kelas_id" class="form-control select2-ajax-kelas" data-placeholder="Semua Kelas">
                                    <option value="">Semua Kelas</option>
                                    <?php if($selectedKelas): ?>
                                        <option value="<?php echo e($selectedKelas->id); ?>" selected><?php echo e($selectedKelas->nama_kelas); ?></option>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="d-flex justify-content-between">
                                <button type="submit" class="btn btn-primary w-100 mr-2"><i class="fas fa-search"></i> Cari</button>
                                <a href="<?php echo e(route('siswa.index')); ?>" class="btn btn-default w-100" title="Reset Filter"><i class="fas fa-sync"></i></a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <?php if(session('failed_rows')): ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h5><i class="icon fas fa-exclamation-triangle"></i> Peringatan Import Excel!</h5>
            <?php echo e(session('warning')); ?>

            <hr>
            <ul class="mb-0">
                <?php $__currentLoopData = session('failed_rows'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e($error); ?></li>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ul>
        </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Data Siswa</h3>
                <div class="card-tools">
                    <a href="<?php echo e(route('siswa.download-template')); ?>" class="btn btn-info btn-sm">
                        <i class="fas fa-download"></i> Template Excel
                    </a>
                    <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#modal-upload">
                        <i class="fas fa-upload"></i> Upload Excel
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#modal-add">
                        <i class="fas fa-plus"></i> Tambah Siswa
                    </button>
                </div>
            </div>
            <!-- /.card-header -->
                <table class="table table-hover text-nowrap align-middle">
                    <thead>
                        <tr>
                            <th style="width: 50px;">NO</th>
                            <th>NIS</th>
                            <th>Nama Lengkap</th>
                            <th>Kelas</th>
                            <th>Kategori</th>
                            <th>L/P</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__empty_1 = true; $__currentLoopData = $siswas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $siswa): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <tr>
                                <td><?php echo e($siswas->firstItem() + $index); ?></td>
                                <td><strong><?php echo e($siswa->nis); ?></strong></td>
                                <td><?php echo e($siswa->nama_lengkap); ?></td>
                                <td>
                                    <?php
                                        // Gunakan siswaKelasHistory jika di-load (filter tahun ajaran historis),
                                        // fallback ke siswaKelas (data aktif saat ini)
                                        $kelasTahunIni = $siswa->relationLoaded('siswaKelasHistory')
                                            ? $siswa->siswaKelasHistory->first()
                                            : ($siswa->relationLoaded('siswaKelas') ? $siswa->siswaKelas->first() : null);
                                        $kelasSiswa = $kelasTahunIni ? $kelasTahunIni->kelas : $siswa->kelas;
                                    ?>
                                    <?php if($kelasSiswa): ?>
                                        <span class="badge badge-info"><?php echo e($kelasSiswa->nama_kelas); ?></span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if($siswa->kategori == 'internal'): ?>
                                        <span class="badge badge-secondary">Internal</span>
                                    <?php else: ?>
                                        <span class="badge badge-dark">External</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo e($siswa->jenis_kelamin); ?></td>
                                <td>
                                    <?php
                                        $statusSiswa = $kelasTahunIni ? $kelasTahunIni->status : $siswa->status;
                                    ?>
                                    <?php if($statusSiswa == 'aktif'): ?>
                                        <span class="badge badge-success">Aktif</span>
                                    <?php elseif($statusSiswa == 'lulus'): ?>
                                        <span class="badge badge-primary">Lulus</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Non Aktif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <!-- Edit Btn -->
                                    <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#modal-edit-<?php echo e($siswa->id); ?>" title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <!-- Status Btn -->
                                    <button type="button" class="btn btn-<?php echo e($siswa->status == 'aktif' ? 'success' : 'danger'); ?> btn-sm" data-toggle="modal" data-target="#modal-status-<?php echo e($siswa->id); ?>" title="Ubah Status">
                                        <i class="fas fa-power-off"></i>
                                    </button>
                                </td>
                            </tr>


                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="8" class="text-center">Belum ada data siswa ditemukan.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="card-footer clearfix">
                <?php echo e($siswas->links('pagination::bootstrap-4')); ?>

            </div>
        </div>
    </div>
</div>

<!-- Render Modals Outside of Bulk Form -->
<?php $__currentLoopData = $siswas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $siswa): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<!-- Edit Modal -->
<div class="modal fade" id="modal-edit-<?php echo e($siswa->id); ?>">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?php echo e(route('siswa.update', $siswa->id)); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>
                <div class="modal-header">
                    <h4 class="modal-title">Edit Siswa (Tanpa Ubah NIS/Kelas)</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>NIS (Unik/Tetap)</label>
                        <input type="text" class="form-control" value="<?php echo e($siswa->nis); ?>" readonly>
                    </div>
                    <div class="form-group">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama_lengkap" class="form-control" value="<?php echo e($siswa->nama_lengkap); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Kategori</label>
                        <select name="kategori" class="form-control" required>
                            <option value="internal" <?php echo e($siswa->kategori == 'internal' ? 'selected' : ''); ?>>Internal (Dari lembaga sendiri)</option>
                            <option value="external" <?php echo e($siswa->kategori == 'external' ? 'selected' : ''); ?>>External (Pindahan/Luar)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Jenis Kelamin</label>
                        <select name="jenis_kelamin" class="form-control" required>
                            <option value="L" <?php echo e($siswa->jenis_kelamin == 'L' ? 'selected' : ''); ?>>Laki-Laki (L)</option>
                            <option value="P" <?php echo e($siswa->jenis_kelamin == 'P' ? 'selected' : ''); ?>>Perempuan (P)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>No WhatsApp</label>
                        <input type="text" name="no_wa" class="form-control" value="<?php echo e($siswa->no_wa); ?>">
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Ubah Status Modal -->
<div class="modal fade" id="modal-status-<?php echo e($siswa->id); ?>">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <form action="<?php echo e(route('siswa.update-status', $siswa->id)); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>
                <div class="modal-header">
                    <h4 class="modal-title">Konfirmasi Status</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Ubah status siswa <b><?php echo e($siswa->nama_lengkap); ?></b>?</p>
                    <input type="hidden" name="status" value="<?php echo e($siswa->status == 'aktif' ? 'tidak_aktif' : 'aktif'); ?>">
                    <?php if($siswa->status == 'aktif'): ?>
                        Menjadi <span class="badge badge-danger">Non Aktif</span><br>
                        <small class="text-muted">Data ini tidak akan terhapus demi menjaga histori transaksi.</small>
                    <?php else: ?>
                        Menjadi <span class="badge badge-success">Aktif</span>
                    <?php endif; ?>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Ya, Ubah Status</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

<!-- Add Modal -->
<div class="modal fade" id="modal-add">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?php echo e(route('siswa.store')); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <div class="modal-header">
                    <h4 class="modal-title">Tambah Siswa Baru</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        Siswa akan ditambahkan ke histori Tahun Ajaran yang Anda pilih di bawah ini tanpa terpengaruh sistem Tahun Ajaran aktif.
                    </div>
                    <div class="form-group">
                        <label>Tahun Ajaran <span class="text-danger">*</span></label>
                        <select name="tahun_ajaran_id" class="form-control select2-ajax-ta modal-ta-add" required data-placeholder="-- Pilih Tahun Ajaran --">
                            <?php if($tahunAktif): ?>
                                <option value="<?php echo e($tahunAktif->id); ?>" selected><?php echo e($tahunAktif->tahun); ?></option>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>NIS (Nomor Induk Siswa)</label>
                        <input type="text" name="nis" class="form-control" value="<?php echo e(old('nis')); ?>" required>
                        <small class="text-danger">* Unik dan tidak bisa diubah nanti.</small>
                    </div>
                    <div class="form-group">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama_lengkap" class="form-control" value="<?php echo e(old('nama_lengkap')); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Kategori</label>
                        <select name="kategori" class="form-control" required>
                            <option value="external" <?php echo e(old('kategori') == 'external' ? 'selected' : ''); ?>>External (Pindahan/Luar)</option>
                            <option value="internal" <?php echo e(old('kategori') == 'internal' ? 'selected' : ''); ?>>Internal (Dari lembaga sendiri)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Jenis Kelamin</label>
                        <select name="jenis_kelamin" class="form-control" required>
                            <option value="">Pilih JK</option>
                            <option value="L" <?php echo e(old('jenis_kelamin') == 'L' ? 'selected' : ''); ?>>Laki-Laki (L)</option>
                            <option value="P" <?php echo e(old('jenis_kelamin') == 'P' ? 'selected' : ''); ?>>Perempuan (P)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>No WhatsApp</label>
                        <input type="text" name="no_wa" class="form-control" value="<?php echo e(old('no_wa')); ?>" placeholder="Contoh: 0812...">
                    </div>
                    <div class="form-group">
                        <label>Masuk Ke Kelas <span class="text-danger">*</span></label>
                        <select name="kelas_id" class="form-control select2-ajax-kelas modal-kelas-add" required data-placeholder="Pilih Kelas">
                        </select>
                        <small class="text-muted">Pastikan memilih kelas yang berada pada rentang Tahun Ajaran yang sama di atas.</small>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan Siswa</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Upload Excel Modal -->
<div class="modal fade" id="modal-upload">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?php echo e(route('siswa.import-excel')); ?>" method="POST" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <div class="modal-header">
                    <h4 class="modal-title">Upload Data Siswa</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="text-muted">1. Download template dengan menekan tombol biru.<br>2. Isi data sesuai petunjuk kolom.<br>3. Upload file yang sudah diisi (.xlsx atau .csv).</p>
                    <div class="form-group">
                        <label>Tahun Ajaran <span class="text-danger">*</span></label>
                        <select name="tahun_ajaran_id" class="form-control select2-ajax-ta modal-ta-upload" required data-placeholder="-- Pilih Tujuan Tahun Ajaran --">
                            <?php if($tahunAktif): ?>
                                <option value="<?php echo e($tahunAktif->id); ?>" selected><?php echo e($tahunAktif->tahun); ?></option>
                            <?php endif; ?>
                        </select>
                        <small class="text-muted">Nama kelas di file Excel harus cocok dengan kelas di Tahun Ajaran ini.</small>
                    </div>
                    <div class="form-group mt-3">
                        <label>File Excel (.xlsx, .csv) <span class="text-danger">*</span></label>
                        <input type="file" name="file_excel" class="form-control" accept=".xlsx,.csv" required>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-success"><i class="fas fa-upload"></i> Proses Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        // Init Select2 for Tahun Ajaran
        $('.select2-ajax-ta').select2({
            theme: 'bootstrap4',
            width: '100%',
            allowClear: true,
            ajax: {
                url: '<?php echo e(route('ajax.tahun-ajaran')); ?>',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return { q: params.term, page: params.page || 1 };
                },
                processResults: function (data) {
                    return { results: data.results, pagination: { more: data.pagination.more } };
                },
                cache: true
            }
        });

        // Init Select2 for Kelas (Dependent on Tahun Ajaran)
        function initDependentKelas(taSelector, kelasSelector) {
            $(kelasSelector).select2({
                theme: 'bootstrap4',
                width: '100%',
                allowClear: true,
                ajax: {
                    url: '<?php echo e(route('ajax.kelas')); ?>',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return { 
                            q: params.term, 
                            tahun_ajaran_id: $(taSelector).val(), // Send currently selected TA
                            page: params.page || 1 
                        };
                    },
                    processResults: function (data) {
                        return { results: data.results, pagination: { more: data.pagination.more } };
                    },
                    cache: true
                }
            });

            // When TA changes, clear the Kelas select so user must re-pick
            $(taSelector).on('change', function() {
                $(kelasSelector).val(null).trigger('change');
            });
        }

        // Apply to Filter Form
        initDependentKelas('select[name="tahun_ajaran_id"]:not(.modal-ta-add, .modal-ta-upload)', 'select[name="kelas_id"]:not(.modal-kelas-add)');
        
        // Apply to Add Modal Form
        initDependentKelas('.modal-ta-add', '.modal-kelas-add');
    });

    <?php if(session('success')): ?>
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: '<?php echo e(session('success')); ?>',
            timer: 3000,
            showConfirmButton: false
        });
    <?php endif; ?>

    <?php if(session('error')): ?>
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: '<?php echo e(session('error')); ?>',
            timer: 3000,
            showConfirmButton: false
        });
    <?php endif; ?>

    <?php if($errors->any()): ?>
        Swal.fire({
            icon: 'error',
            title: 'Terdapat Kesalahan',
            html: '<?php echo implode("<br>", $errors->all()); ?>'
        });
    <?php endif; ?>
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Herd\spp_app\resources\views/siswa/index.blade.php ENDPATH**/ ?>