@extends('backend.layout.template_bk')
@section('content')

<div class="row">
  <div class="col-12 col-md-6 col-lg-4 mb-4 ml-md-3">
    <div class="dropdown w-100">
      <button class="btn btn-danger dropdown-toggle w-100" type="button" id="dropdownMenuSizeButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Pilih Kelas
      </button>
      <div class="dropdown-menu w-100" aria-labelledby="dropdownMenuSizeButton2">
        @foreach($dropdownKelas as $kelas)
          @php
            $param = $kelas->nama . '-' . $kelas->tahun_ajaran_id;
          @endphp
          <a class="dropdown-item {{ request('kelas') === $param ? 'active' : '' }}" 
             href="{{ route('backend.bk.nilai', ['kelas' => $param]) }}">
            {{ $kelas->nama }} - {{ $kelas->tahunAjaran->tahun_awal }}/{{ $kelas->tahunAjaran->tahun_akhir }}
          </a>
          <div class="dropdown-divider"></div>
        @endforeach
      </div>
    </div>
  </div>
</div>


@if($kelases->isNotEmpty())
  @foreach($kelases as $kelas)
    <div class="col-lg-12 grid-margin stretch-card mb-4">
      <div class="card">
        <div class="card-body">
          <div class="row mb-3 d-flex justify-content-between">
            <div class="col-12 col-sm-6 col-md-3">
              <h4 class="card-title mt-1">NILAI KELAS <strong class="text-danger">{{ $kelas->nama }}</strong></h4>
            </div>
            <div class="col-12 col-sm-6 col-md-3 mb-2">
              <code class="ms-2" style="font-weight: bold;">
                Semester {{ $kelas->semester->semester }}
                - {{ $kelas->tahunAjaran->tahun_awal }}/{{ $kelas->tahunAjaran->tahun_akhir }}
              </code>
            </div>
            <div class="col-12 col-sm-6 col-md-3 mb-2">
              <form>
                <input id="search-input" class="form-control w-100 search-siswa" type="search" placeholder="Search NISN / Nama" aria-label="Search">
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table table-striped table-siswa">
              <thead>
                <tr class="text-center">
                  <th>NISN</th>
                  <th>Nama</th>
                  @foreach($kelas->kelasMapel as $km)
                    @if($km->mapel->tipe != 0)
                      <th>{{ $km->mapel->nama }}</th>
                    @endif
                  @endforeach
                  <th>Aksi</th>
                </tr>
              </thead>
              <tbody>
                @foreach($kelas->siswaKelas as $sk)
                  <tr class="text-center">
                    <td class="nisn">{{ $sk->siswa->nisn }}</td>
                    <td class="nama">{{ $sk->siswa->user->name }}</td>
                    @foreach($kelas->kelasMapel as $km)
                      @if($km->mapel->tipe != 0)
                        @php
                          $nilai = $km->nilai->firstWhere('siswa_id', $sk->siswa->siswa_id);
                          $arr   = is_string($nilai?->s_nilai)
                                    ? json_decode($nilai->s_nilai, true)
                                    : ($nilai?->s_nilai ?? []);

                          $filled = array_filter($arr, fn($v) => $v !== null);
                          $jumlahPenilaian = count($filled);

                          $avgDisplay = $jumlahPenilaian
                          ? round(array_sum($filled) / $jumlahPenilaian) . ' <span class="text-muted">/ ' . $jumlahPenilaian . ' penilaian</span>'
                          : 'belum ada nilai';
                        @endphp
                        <td class="{{ $jumlahPenilaian ? 'text-dark' : 'text-danger' }}">
                           {!! $avgDisplay !!}
                        </td>
                      @endif  
                    @endforeach
                    <td>
                      <button class="btn btn-sm btn-primary" title="Detail" data-toggle="modal" data-target="#detailModal-{{ $kelas->id }}-{{ $sk->siswa->siswa_id }}">
                        <i class="mdi mdi-eye"></i>
                      </button>
                    </td>
                  </tr>
                @endforeach
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    @foreach($kelases as $kelas)
      @foreach($kelas->siswaKelas as $sk)
        <div class="modal fade" id="detailModal-{{ $kelas->id }}-{{ $sk->siswa->siswa_id }}" tabindex="-1" role="dialog">
          <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Detail Nilai 
                  <span class="text-danger" style="font-weight: bold;">
                    {{ $sk->siswa->user->name }} ({{ $sk->siswa->nisn }})
                  </span>
                </h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
              </div>
              <div class="modal-body">
                @foreach($kelas->kelasMapel as $km)
                @php
                  $nilaiModel = $km->nilai->firstWhere('siswa_id', $sk->siswa->siswa_id);
                  $raw        = $nilaiModel?->s_nilai;
                  $nilaiArr   = is_string($raw) ? json_decode($raw, true) : ($raw ?? []);
                  $labels     = array_keys($nilaiArr);
                  $filled     = array_filter($nilaiArr, fn($v) => $v !== null);
                  $avg        = count($filled)
                                  ? round(array_sum($filled) / count($filled))
                                  : '-';
                @endphp

                <div class="mb-2 text-primary">
                  <strong><span class="text-dark">Mapel :</span> {{ $km->mapel->nama }}</strong><br>
                  <strong><span class="text-dark">Pengajar :</span> {{ $km->guru->user->name }}</strong>
                </div>

                @if($km->mapel->tipe == 0)
                  <div class="alert alert-success text-center">
                    Tidak ada penilaian di mapel <strong>{{ $km->mapel->nama }}</strong>.
                  </div>
                @else
                  @if(!empty($labels))
                    <div class="table-responsive mb-4">
                      <table class="table table-striped text-center">
                        <thead>
                          <tr>
                            @foreach($labels as $label)
                              <th>{{ $label }}</th>
                            @endforeach
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            @foreach($labels as $label)
                              <td class="{{ isset($nilaiArr[$label]) ? '' : 'text-danger' }}">
                                {{ $nilaiArr[$label] ?? 'belum ada nilai' }}
                              </td>
                            @endforeach
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  @else
                    <div class="text-muted">Belum ada nilai untuk mapel <strong>{{ $km->mapel->nama }}</strong>.</div>
                  @endif
                @endif

              @endforeach
              </div>
            </div>
          </div>
        </div>
      @endforeach
    @endforeach
  @endforeach
@else
  <div class="alert alert-warning">Silahkan pilih kelas terlebih dahulu.</div>
@endif

<script>
  document.addEventListener('DOMContentLoaded', function () {
    // Ambil semua input search yang pakai class `search-siswa`
    const searchInputs = document.querySelectorAll('.search-siswa');

    searchInputs.forEach(function (input) {
      input.addEventListener('keyup', function () {
        const searchValue = input.value.toLowerCase();

        // Cari elemen table terdekat (yang ada di dalam parent yang sama)
        const table = input.closest('.card-body').querySelector('.table-siswa');
        const rows = table.querySelectorAll('tbody tr');

        rows.forEach(function (row) {
          const nisn = row.querySelector('.nisn')?.textContent.toLowerCase() || '';
          const nama = row.querySelector('.nama')?.textContent.toLowerCase() || '';
          const combined = nisn + ' ' + nama;

          row.style.display = combined.includes(searchValue) ? '' : 'none';
        });
      });
    });
  });
</script>

@endsection