  @extends('backend.layout.template_guru')
  @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.guru.penilaian', ['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="d-flex justify-content-between mb-2">
            <h4 class="card-title mt-1">NILAI SISWA</h4>
            <code class="ms-2" style="font-weight: bold;">
              Kelas {{ $kelas->nama }}
              - Semester {{ $kelas->semester->semester }}
              - {{ $kelas->tahunAjaran->tahun_awal }}/{{ $kelas->tahunAjaran->tahun_akhir }}
            </code>
          </div>

    @foreach($kelas->kelasMapel as $km)
      @php
                $raw    = $km->nilai->first()?->s_nilai;
                $assoc  = is_string($raw) ? json_decode($raw, true) : ($raw ?? []);
                $labels = array_keys($assoc);
              @endphp
              @php
                $arrRaw = $assoc;
                $count = count($arrRaw) ?: count($labels);
              @endphp

      {{-- Baris Tombol --}}
      <div class="row mb-3">
        {{-- Tombol Rapor --}}
        <div class="col-12 col-sm-6 col-md-3 mb-2">
          <button type="button"
                  class="btn btn-success w-100"
                  data-toggle="modal"
                  data-target="#raporModal-{{ $km->id }}">
            <i class="bi bi-journal-text btn-icon-prepend mr-1"></i> Nilai Rata-Rata
          </button>
        </div>

        <!-- Tombol Import -->
    <div class="col-12 col-sm-6 col-md-3 mb-2">
      <button type="button" class="btn btn-dark w-100"
            data-toggle="modal"
            data-target="#uploadModal-{{ $km->id }}">
        <i class="bi bi-arrow-down-up btn-icon-prepend mr-1"></i> Import & Export
      </button>
    </div>

    <!-- Search -->
    <div class="col-12 col-sm-6 col-md-3 mb-2">
      <form>
        <input
    class="form-control w-100 search-siswa"
    type="search"
    placeholder="Cari Nama/NISN"
    aria-label="Search"
  />
      </form>
    </div>

        {{-- Dropdown Sumatif --}}
        <div class="col-12 col-sm-6 col-md-3 mb-2">
          <form action="{{ route('guru.penilaian.updateJumlahSumatif') }}" method="POST" id="sumatifForm{{ $km->id }}">
            @csrf
            <input type="hidden" name="kelas_mapel_id" value="{{ $km->id }}">
            <input type="hidden" name="kelas" value="{{ $selectedKey }}">
            <input type="hidden" name="count" id="sumatifCount{{ $km->id }}" value="{{ $count }}">
            <div class="position-relative">
              <button type="button" class="btn btn-primary dropdown-toggle w-100" onclick="toggleDropdown({{ $km->id }})">
                Jumlah Sumatif
              </button>
              <div id="dropdown{{ $km->id }}" class="dropdown-menu dropdown-menu-end w-100"
                  style="display: none; position: absolute; right: 0; top: 100%; z-index: 999;">
                <h6 class="dropdown-header">Pilih Jumlah Sumatif</h6>
                @for($i = 1; $i <= 10; $i++)
                  <a class="dropdown-item @if($count == $i) active @endif"
                    href="#"
                    onclick="event.preventDefault(); confirmSubmit('{{ $i }}', '{{ $km->id }}')">
                    {{ $i }}
                  </a>
                @endfor
              </div>
            </div>
          </form>
        </div>
      </div>

      {{-- Modal Rapor --}}
      <div class="modal fade" id="raporModal-{{ $km->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 Siswa</h5>
              <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="d-flex flex-column flex-md-row justify-content-md-between mb-3">
                <p class="mb-1 fw-bold">
                  <strong> Mapel : </strong> 
                  <span class="text-danger">{{ $km->mapel->nama }}</span>
                </p>
                <p class="mb-1 text-md-end fw-bold">
                  <strong> Kelas : </strong> 
                  <span class="text-danger">
                    {{ $km->kelas->nama }} - Semester {{ $km->kelas->semester->semester }} -
                    {{ $km->kelas->tahunAjaran->tahun_awal }}/{{ $km->kelas->tahunAjaran->tahun_akhir }}
                  </span>
                </p>
              </div>
              <div class="table-responsive mt-3">
                <table class="table table-striped text-center">
                  <thead>
                    <tr>
                      <th>NISN</th>
                      <th>Nama</th>
                      <th>Nilai Rata-Rata</th>
                    </tr>
                  </thead>
                  <tbody>
                    @foreach($kelas->siswaKelas as $sk)
                      @php
                        $nm  = $km->nilai->firstWhere('siswa_id', $sk->siswa->siswa_id);
                        $raw = is_string($nm?->s_nilai)
                                ? json_decode($nm->s_nilai, true)
                                : ($nm?->s_nilai ?? []);
                        
                        $filledVals = array_filter($raw, fn($v) => $v !== null);
                        
                        $avg = count($filledVals)
                              ? round(array_sum($filledVals) / count($filledVals))
                              : '-';
                      @endphp
                      <tr>
                        <td>{{ $sk->siswa->nisn }}</td>
                        <td>{{ $sk->siswa->user->name }}</td>
                        <td title="Rata-rata dari {{ count($filledVals) }} penilaian">
                          @if($avg !== '-')
                            {{ $avg }} <span class="text-muted"> / {{ count($filledVals) }} Penilaian</span>
                          @else
                            -
                          @endif
                        </td>
                      </tr>
                    @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>

      <!-- modal upload -->
  <div class="modal fade" id="uploadModal-{{ $km->id }}" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header d-flex justify-content-between align-items-center">
          <h5 class="modal-title" id="uploadModalLabel">Upload File Excel</h5>
          <div>
            <button type="button"
              id="btnExportNilai"
              class="btn btn-primary"
              onclick="window.location='{{ route('guru.penilaian.exportNilai', $km->id) }}'"> Export Nilai
            </button>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
        </div>
        <form action="{{ route('guru.penilaian.importNilai', $km->id) }}" method="POST" enctype="multipart/form-data">
          @csrf
          <div class="modal-body">
            <div class="form-group">
              <label for="file">File Excel Nilai (xlsx)</label>
              <input type="file" name="file" class="form-control" required>
            </div>
          </div>    
          <div class="modal-footer w-100">
            <div class="row w-100 d-flex justify-content-between">
              <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 class="col-12 col-lg-auto mb-2">
                <button type="submit" class="btn btn-dark w-100 w-lg-auto">Import</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>

      {{-- Tabel Nilai --}}
      <div class="table-responsive mb-4">
        <table class="table table-striped table-siswa text-center" data-kelas-mapel="{{ $km->id }}" id="tbl-{{ $km->id }}">
          <thead>
            <tr>
              <th>NISN</th>
              <th>Nama</th>
              @foreach($labels as $idx => $label)
                <th contenteditable="true" data-label-idx="{{ $idx }}" class="editable-header">{{ $label }}</th>
              @endforeach
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            @foreach($kelas->siswaKelas as $sk)
              @php
                $rowRaw = $km->nilai->firstWhere('siswa_id', $sk->siswa->siswa_id)?->s_nilai;
                $rowAssoc = is_string($rowRaw) ? json_decode($rowRaw, true) : ($rowRaw ?? []);
              @endphp
              <tr>
                <td class="nisn">{{ $sk->siswa->nisn }}</td>
                <td class="nama">{{ $sk->siswa->user->name }}</td>
                @foreach($labels as $label)
                  <td class="{{ isset($rowAssoc[$label]) ? '' : 'text-danger' }}">
                    {{ $rowAssoc[$label] ?? 'belum ada nilai' }}
                  </td>
                @endforeach
                <td>
                  <button class="btn btn-sm btn-warning text-white"
                          data-toggle="modal"
                          title="Edit"
                          data-target="#detailModal-{{ $km->id }}-{{ $sk->siswa->siswa_id }}">
                    <i class="mdi mdi-pencil"></i>
                  </button>
                </td>
              </tr>

              {{-- Modal Edit Nilai --}}
              <div class="modal fade" id="detailModal-{{ $km->id }}-{{ $sk->siswa->siswa_id }}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title">Edit Nilai  
                        <span class="text-danger fw-bold">
                          {{ $sk->siswa->user->name }} ({{ $sk->siswa->nisn }})
                        </span>
                      </h5>
                      <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    </div>
                    <form action="{{ route('guru.penilaian.updateNilai') }}" method="POST">
                      @csrf @method('PUT')
                      <input type="hidden" name="kelas_mapel_id" value="{{ $km->id }}">
                      <input type="hidden" name="siswa_id" value="{{ $sk->siswa->siswa_id }}">
                      <div class="modal-body">
                        <div class="row">
                          @foreach($labels as $idx => $label)
                            <div class="col-md-4 mb-3">
                              <div class="form-group">
                                <label>{{ $label }}</label>
                                <input type="number" name="nilai[{{ $idx }}]" class="form-control" value="{{ $rowAssoc[$label] ?? '' }}">
                              </div>
                            </div>
                          @endforeach
                        </div>
                      </div>
                      <div class="modal-footer w-100">
                        <div class="row w-100 d-flex justify-content-between">
                          <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 class="col-12 col-lg-auto mb-2">
                            <button type="submit" class="btn btn-warning w-100 w-lg-auto">Update</button>
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            @endforeach
          </tbody>
        </table>
      </div>
    @endforeach
  </div>
        </div>
      </div>
    @endforeach
  @else
    <div class="alert alert-warning">Silahkan pilih kelas terlebih dahulu.</div>
  @endif

  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <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>

  <style>
  .swal-popup-tall {
    height: 400px !important;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  </style>

  <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>

  <script>
    document.getElementById('btnExportNilai').addEventListener('click', function () {
      window.location.href = "#";
    });
  </script>

  <script>
    function toggleDropdown(id) {
      const menu = document.getElementById(`dropdown${id}`);
      menu.style.display = menu.style.display === 'none' || menu.style.display === '' ? 'block' : 'none';

      document.addEventListener('click', function (e) {
        if (!e.target.closest(`#dropdown${id}`) && !e.target.closest(`button[onclick*="toggleDropdown(${id})"]`)) {
          menu.style.display = 'none';
        }
      });
    }

    function confirmSubmit(value, kmId) {
      Swal.fire({
        title: 'Yakin Ubah Jumlah Sumatif?',
        text: `Jumlah Sumatif akan diubah menjadi ${value}`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Ubah!',
        cancelButtonText: 'Batal',
        customClass: { popup: 'swal-popup-tall' }
      }).then((result) => {
        if (result.isConfirmed) {
          document.getElementById(`sumatifCount${kmId}`).value = value;
          document.getElementById(`sumatifForm${kmId}`).submit();
        }
      });
    }
  </script>

  <script>
    // ensure SweetAlert2 is loaded first
    document.querySelectorAll('.editable-header').forEach(th => {
      // stash the original
      th.dataset.originalLabel = th.textContent.trim();

      th.addEventListener('keydown', async e => {
        if (e.key !== 'Enter') return;
        // STOP the browser from inserting a newline or moving focus
        e.preventDefault();
        e.stopImmediatePropagation();

        const newText = th.textContent.trim();
        const oldText = th.dataset.originalLabel;
        if (newText === oldText) return; 

        // CONFIRM dialog
        const { isConfirmed } = await Swal.fire({
          title: 'Yakin ingin mengganti header nilai?',
          text: `"${oldText}" → "${newText}"`,
          icon: 'question',
          showCancelButton: true,
          confirmButtonText: 'Ya, ganti',
          cancelButtonText: 'Batal',
          customClass: { popup: 'swal-popup-tall' },
        });

        if (!isConfirmed) {
          // rollback to original
          th.textContent = oldText;
          return;
        }

        // update the data-original for future edits
        th.dataset.originalLabel = newText;

        // collect and send all headers
        const table = th.closest('table');
        const kmId  = table.dataset.kelasMapel;
        const form  = new FormData();
        form.append('_token', '{{ csrf_token() }}');
        form.append('kelas_mapel_id', kmId);
        form.append('kelas', '{{ $selectedKey }}');
        table.querySelectorAll('.editable-header').forEach(hdr => {
          form.append(`labels[${hdr.dataset.labelIdx}]`, hdr.textContent.trim());
        });

        try {
          await fetch('{{ route("guru.penilaian.updateLabelSumatif") }}', {
            method: 'POST',
            body: form
          });

          // success toast
          await Swal.fire({
            title: 'Berhasil!',
            text: 'Header nilai telah diperbarui.',
            icon: 'success',
            timer: 1500,
            showConfirmButton: false,
            customClass: { popup: 'swal-popup-tall' }
          });

          window.location.reload();

        } catch (err) {
          console.error(err);
          Swal.fire('Error', 'Gagal menyimpan header.', 'error');
        }
      });
    });
  </script>

  @endsection