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

@php
  $currentParam = request('kelas');
@endphp

<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="dropdownKelas" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Pilih Kelas
      </button>
      <div class="dropdown-menu w-100" aria-labelledby="dropdownKelas">
        @foreach($dropdownKelas as $kelas)
          @php
            $param = $kelas->nama . '-' . $kelas->tahun_ajaran_id;
            $isActive = ($currentParam === $param);
          @endphp
          <a class="dropdown-item {{ $isActive ? 'active bg-primary text-white' : '' }}"
             href="{{ route('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">
            <div class="col-12 col-md-4 mb-2 d-flex align-items-center">
              <h4 class="card-title mb-0">NILAI SISWA</h4>
            </div>
            <div class="col-12 col-md-4 mb-2 d-flex align-items-center">
              <code class="w-100 text-md-center" style="font-weight: bold;">
                Kelas {{ $kelas->nama }} - Semester {{ $kelas->semester->semester }}
                - {{ $kelas->tahunAjaran->tahun_awal }}/{{ $kelas->tahunAjaran->tahun_akhir }}
              </code>
            </div>
            <div class="col-12 col-md-4 mb-2 d-flex justify-content-md-end">
              <button type="button"
        class="btn btn-primary btn-sm w-100 w-md-auto"
        data-toggle="modal"
        data-target="#raporModal-{{ $kelas->id }}">
  <i class="bi bi-journal-text me-1"></i> Nilai Rata-Rata
</button>

            </div>
          </div>
        @foreach($kelas->kelasMapel as $km)
  <hr class="my-3" style="border-top: 1px solid #000;" />
  <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
    @php
      $nilaiModel = $km->nilai->first();
      $raw        = $nilaiModel?->s_nilai;
      $nilaiArr   = is_string($raw) ? json_decode($raw, true) : ($raw ?? []);
      $labels     = array_keys($nilaiArr);
    @endphp
    <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>
  @endif
@endforeach

        <!-- Modal Rapor -->
        <div class="modal fade" id="raporModal-{{ $kelas->id }}" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title mb-0">Data Nilai Rata-Rata</h5>
                <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="card-description d-flex justify-content-center">
                  <code class="ms-2 fw-bold" style="font-weight: bold;">
                    Kelas {{ $kelas->nama }} 
                    - Semester {{ $kelas->semester->semester }} 
                    - {{ $kelas->tahunAjaran->tahun_awal }}/{{ $kelas->tahunAjaran->tahun_akhir }}
                  </code>
                </p>
                <div class="table-responsive">
                  <table class="table table-striped text-center">
                    <thead>
                      <tr>
                        <th>Mata Pelajaran</th>
                        <th>Nilai Rata-rata</th>
                        <th>Total Sumatif</th>
                      </tr>
                    </thead>
                    <tbody>
                      @php
                        $siswaId = auth()->user()->siswa->siswa_id;
                      @endphp
                      @foreach($kelas->kelasMapel as $km)
                        @if($km->mapel->tipe)
                          @php
                            $nilai    = $km->nilai->firstWhere('siswa_id', $siswaId);
                            $nilaiArr = is_string($nilai?->s_nilai)
                                          ? json_decode($nilai->s_nilai, true)
                                          : ($nilai?->s_nilai ?? []);
                            
                            $filled = array_filter($nilaiArr, fn($v) => $v !== null);
                            $jumlahTerisi = count($filled);
                            $jumlahField = count(array_keys($nilaiArr));

                            $avg = $jumlahTerisi
                                  ? round(array_sum($filled) / $jumlahTerisi)
                                  : null;
                          @endphp
                          <tr>
                            <td>{{ $km->mapel->nama }}</td>
                            <td>
                              @if($avg !== null)
                                {{ $avg }} <span class="text-muted">/ {{ $jumlahTerisi }} penilaian</span>
                              @else
                                <span class="text-danger">belum ada nilai</span>
                              @endif
                            </td>
                            <td>{{ $jumlahField }}</td>
                          </tr>
                        @endif
                      @endforeach
                    </tbody>
                  </table>
                </div>
              </div>
              <div class="modal-footer w-100">
                <div class="row w-100 d-flex justify-content-center">
                  <div class="col-12 col-lg-auto mb-2">
                    <button type="button" class="btn btn-secondary w-100 w-lg-auto" data-dismiss="modal">Tutup</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
@endforeach
@else
  <div class="alert alert-warning">Silahkan pilih kelas terlebih dahulu.</div>
@endif

<script>
    @if (session('success'))
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: '{{ session('success') }}',
            confirmButtonColor: '#3085d6',
            customClass: {
                popup: 'swal-popup-tall',
            }
        });
    @endif

    @if ($errors->any())
        Swal.fire({
            icon: 'error',
            title: 'Gagal!',
            text: '{{ $errors->first() }}',
            confirmButtonColor: '#d33',
            customClass: {
                popup: 'swal-popup-tall',
            }
        });
    @endif
</script>

@endsection
