@extends('layouts.app')

@section('title', 'Manajemen Data Siswa')

@section('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="{{ 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="{{ 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" {{ request('status') == 'aktif' ? 'selected' : '' }}>Aktif</option>
                                    <option value="tidak_aktif" {{ request('status') == 'tidak_aktif' ? 'selected' : '' }}>Non Aktif</option>
                                    <option value="lulus" {{ 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" {{ request('kategori') == 'internal' ? 'selected' : '' }}>Internal</option>
                                    <option value="external" {{ 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>
                                    @if($selectedTa)
                                        <option value="{{ $selectedTa->id }}" selected>{{ $selectedTa->tahun }}</option>
                                    @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>
                                    @if($selectedKelas)
                                        <option value="{{ $selectedKelas->id }}" selected>{{ $selectedKelas->nama_kelas }}</option>
                                    @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="{{ 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>

        @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>
            {{ session('warning') }}
            <hr>
            <ul class="mb-0">
                @foreach (session('failed_rows') as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
        @endif

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Data Siswa</h3>
                <div class="card-tools">
                    <a href="{{ 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>
                        @forelse ($siswas as $index => $siswa)
                            <tr>
                                <td>{{ $siswas->firstItem() + $index }}</td>
                                <td><strong>{{ $siswa->nis }}</strong></td>
                                <td>{{ $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;
                                    @endphp
                                    @if($kelasSiswa)
                                        <span class="badge badge-info">{{ $kelasSiswa->nama_kelas }}</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td>
                                    @if($siswa->kategori == 'internal')
                                        <span class="badge badge-secondary">Internal</span>
                                    @else
                                        <span class="badge badge-dark">External</span>
                                    @endif
                                </td>
                                <td>{{ $siswa->jenis_kelamin }}</td>
                                <td>
                                    @php
                                        $statusSiswa = $kelasTahunIni ? $kelasTahunIni->status : $siswa->status;
                                    @endphp
                                    @if($statusSiswa == 'aktif')
                                        <span class="badge badge-success">Aktif</span>
                                    @elseif($statusSiswa == 'lulus')
                                        <span class="badge badge-primary">Lulus</span>
                                    @else
                                        <span class="badge badge-danger">Non Aktif</span>
                                    @endif
                                </td>
                                <td>
                                    <!-- Edit Btn -->
                                    <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#modal-edit-{{ $siswa->id }}" title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <!-- Status Btn -->
                                    <button type="button" class="btn btn-{{ $siswa->status == 'aktif' ? 'success' : 'danger' }} btn-sm" data-toggle="modal" data-target="#modal-status-{{ $siswa->id }}" title="Ubah Status">
                                        <i class="fas fa-power-off"></i>
                                    </button>
                                </td>
                            </tr>


                        @empty
                            <tr>
                                <td colspan="8" class="text-center">Belum ada data siswa ditemukan.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            <div class="card-footer clearfix">
                {{ $siswas->links('pagination::bootstrap-4') }}
            </div>
        </div>
    </div>
</div>

<!-- Render Modals Outside of Bulk Form -->
@foreach ($siswas as $siswa)
<!-- Edit Modal -->
<div class="modal fade" id="modal-edit-{{ $siswa->id }}">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('siswa.update', $siswa->id) }}" method="POST">
                @csrf
                @method('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="{{ $siswa->nis }}" readonly>
                    </div>
                    <div class="form-group">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama_lengkap" class="form-control" value="{{ $siswa->nama_lengkap }}" required>
                    </div>
                    <div class="form-group">
                        <label>Kategori</label>
                        <select name="kategori" class="form-control" required>
                            <option value="internal" {{ $siswa->kategori == 'internal' ? 'selected' : '' }}>Internal (Dari lembaga sendiri)</option>
                            <option value="external" {{ $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" {{ $siswa->jenis_kelamin == 'L' ? 'selected' : '' }}>Laki-Laki (L)</option>
                            <option value="P" {{ $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="{{ $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-{{ $siswa->id }}">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <form action="{{ route('siswa.update-status', $siswa->id) }}" method="POST">
                @csrf
                @method('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>{{ $siswa->nama_lengkap }}</b>?</p>
                    <input type="hidden" name="status" value="{{ $siswa->status == 'aktif' ? 'tidak_aktif' : 'aktif' }}">
                    @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>
                    @else
                        Menjadi <span class="badge badge-success">Aktif</span>
                    @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>
@endforeach

<!-- Add Modal -->
<div class="modal fade" id="modal-add">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('siswa.store') }}" method="POST">
                @csrf
                <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 --">
                            @if($tahunAktif)
                                <option value="{{ $tahunAktif->id }}" selected>{{ $tahunAktif->tahun }}</option>
                            @endif
                        </select>
                    </div>
                    <div class="form-group">
                        <label>NIS (Nomor Induk Siswa)</label>
                        <input type="text" name="nis" class="form-control" value="{{ 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="{{ old('nama_lengkap') }}" required>
                    </div>
                    <div class="form-group">
                        <label>Kategori</label>
                        <select name="kategori" class="form-control" required>
                            <option value="external" {{ old('kategori') == 'external' ? 'selected' : '' }}>External (Pindahan/Luar)</option>
                            <option value="internal" {{ 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" {{ old('jenis_kelamin') == 'L' ? 'selected' : '' }}>Laki-Laki (L)</option>
                            <option value="P" {{ 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="{{ 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="{{ route('siswa.import-excel') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <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 --">
                            @if($tahunAktif)
                                <option value="{{ $tahunAktif->id }}" selected>{{ $tahunAktif->tahun }}</option>
                            @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>

@endsection

@push('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: '{{ 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: '{{ 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');
    });

    @if(session('success'))
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: '{{ session('success') }}',
            timer: 3000,
            showConfirmButton: false
        });
    @endif

    @if(session('error'))
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: '{{ session('error') }}',
            timer: 3000,
            showConfirmButton: false
        });
    @endif

    @if($errors->any())
        Swal.fire({
            icon: 'error',
            title: 'Terdapat Kesalahan',
            html: '{!! implode("<br>", $errors->all()) !!}'
        });
    @endif
</script>
@endpush
