@extends('admin.layouts.app')

@section('title', 'Daftar Guru')

@section('content')

<style>
    .page-title {
        font-size: 30px;
        font-weight: 800;
        margin-bottom: 10px;
        margin-top: -20px;
    }

    .custom-card {
        background: white;
        border-radius: 20px;
        border: 2px solid #e5e5e5;
        padding: 25px;
    }

    .btn-primary-custom {
        background: #2b8ef3;
        color: white;
        border-radius: 10px;
        padding: 8px 18px;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        text-decoration: none;
        cursor: pointer;
    }

    .table-header { background: #a5e6ba; }

    .search-box {
        background: #a5e6ba;
        border-radius: 30px;
        padding: 6px 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .search-box input {
        border: none;
        outline: none;
        background: transparent;
        width: 150px;
    }

    .action-icon { width: 20px; cursor: pointer; margin: 0 5px; }

    .per-page-select {
        border-radius: 10px;
        padding: 5px;
        border: 1px solid #ccc;
    }

    .modal-header-pastel {
        background: #FFD97D !important;
        color: black !important;
        border-bottom: none;
    }

    .modal-content {
        border-radius: 20px;
        border: none;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    }

    .modal-body label { font-weight: bold; }

    /* ===== PASANGAN MAPEL - KELAS ===== */
    .mengajar-row {
        display: flex;
        gap: 10px;
        align-items: center;
        background: #f8fafc;
        border-radius: 10px;
        padding: 10px 12px;
        margin-bottom: 8px;
        border: 1px solid #e2e8f0;
    }

    .mengajar-row select {
        flex: 1;
        border-radius: 8px;
        border: 1px solid #cbd5e1;
        padding: 6px 10px;
        font-size: 14px;
    }

    .btn-hapus-row {
        background: #fee2e2;
        color: #ef4444;
        border: none;
        border-radius: 8px;
        width: 32px;
        height: 32px;
        font-size: 16px;
        cursor: pointer;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background 0.2s;
    }

    .btn-hapus-row:hover { background: #fca5a5; }

    .btn-tambah-row {
        background: #e6f0ff;
        color: #2b8ef3;
        border: none;
        border-radius: 8px;
        padding: 7px 14px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        margin-top: 4px;
        transition: background 0.2s;
    }

    .btn-tambah-row:hover { background: #bfdbfe; }

    .row-label {
        font-size: 12px;
        color: #64748b;
        font-weight: 600;
        min-width: 50px;
    }

    .alert-success-custom {
        background: #dcfce7;
        color: #166534;
        border-radius: 10px;
        padding: 12px 16px;
        margin-bottom: 16px;
        font-weight: 500;
    }
</style>

<h3 class="page-title">DAFTAR GURU</h3>

@if(session('success'))
    <div class="alert-success-custom">✅ {{ session('success') }}</div>
@endif

<div class="custom-card">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="d-flex gap-2">
            <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#modalTambah">
                <img src="{{ asset('images/icon/main/add.png') }}" width="18">
                Tambah Data
            </button>
            <button class="btn-primary-custom">
                <img src="{{ asset('images/icon/main/download.png') }}" width="18">
                Download PDF
            </button>
            <button class="btn-primary-custom">
                <img src="{{ asset('images/icon/main/download.png') }}" width="18">
                Download Excel
            </button>
        </div>

        <form method="GET" action="{{ route('admin.guru.index') }}">
            <div class="search-box">
                <input type="text" name="search" placeholder="Cari" value="{{ request('search') }}">
                <button style="border:none;background:none">
                    <img src="{{ asset('images/icon/main/search.png') }}" width="18">
                </button>
            </div>
        </form>
    </div>

    <form method="GET" class="mb-2">
        <span>Tampilkan</span>
        <select name="perPage" onchange="this.form.submit()" class="per-page-select">
            <option value="10"  {{ request('perPage') == 10  ? 'selected' : '' }}>10</option>
            <option value="25"  {{ request('perPage') == 25  ? 'selected' : '' }}>25</option>
            <option value="50"  {{ request('perPage') == 50  ? 'selected' : '' }}>50</option>
            <option value="100" {{ request('perPage') == 100 ? 'selected' : '' }}>100</option>
        </select>
        <span>data</span>
        <input type="hidden" name="search" value="{{ request('search') }}">
    </form>

    <table class="table text-center align-middle">
        <thead class="table-header">
            <tr>
                <th>No</th>
                <th>Nama Lengkap</th>
                <th>NIP</th>
                <th>Mapel</th>
                <th>Kelas</th>
                <th>Password</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
            @forelse($gurus as $index => $guru)
            <tr>
                <td>{{ $gurus->firstItem() + $index }}</td>
                <td>{{ $guru->nama }}</td>
                <td>{{ $guru->nip }}</td>

                <td>
                    @forelse($guru->mengajars as $m)
                        <div>{{ optional($m->mapel)->nama_mapel ?? '-' }}</div>
                    @empty
                        <span class="text-muted">-</span>
                    @endforelse
                </td>

                <td>
                    @forelse($guru->mengajars as $m)
                        <div>{{ optional($m->kelas)->tingkat }} {{ optional($m->kelas)->nama_kelas }}</div>
                    @empty
                        <span class="text-muted">-</span>
                    @endforelse
                </td>

                <td>********</td>

                <td>
                    {{-- TOMBOL EDIT --}}
                    <button onclick="openEditModal(
                        '{{ $guru->id_guru }}',
                        '{{ $guru->nip }}',
                        '{{ addslashes($guru->nama) }}',
                        {{ $guru->mengajars->map(fn($m) => ['id_mapel' => $m->id_mapel, 'id_kelas' => $m->id_kelas])->toJson() }}
                    )" style="border:none;background:none">
                        <img src="{{ asset('images/icon/main/edit.png') }}" class="action-icon">
                    </button>

                    {{-- TOMBOL HAPUS --}}
                    <form action="{{ route('admin.guru.destroy', $guru->id_guru) }}"
                          method="POST" class="d-inline"
                          onsubmit="return confirm('Yakin hapus guru ini?')">
                        @csrf
                        @method('DELETE')
                        <button type="submit" style="border:none;background:none">
                            <img src="{{ asset('images/icon/main/del.png') }}" class="action-icon">
                        </button>
                    </form>
                </td>
            </tr>
            @empty
            <tr>
                <td colspan="7" class="text-muted">Belum ada data guru.</td>
            </tr>
            @endforelse
        </tbody>
    </table>

    <div class="d-flex justify-content-end">
        {{ $gurus->links() }}
    </div>
</div>


{{-- ============================================================ --}}
{{-- MODAL TAMBAH DATA                                            --}}
{{-- ============================================================ --}}
<div class="modal fade" id="modalTambah" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header modal-header-pastel">
        <h5 class="modal-title">Tambah Data Guru</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <form action="{{ route('admin.guru.store') }}" method="POST">
        @csrf
        <div class="modal-body">

          <div class="mb-3">
            <label>NIP <span class="text-danger">*</span></label>
            <input type="text" name="nip" class="form-control" placeholder="Masukkan NIP" required>
          </div>

          <div class="mb-3">
            <label>Nama Lengkap <span class="text-danger">*</span></label>
            <input type="text" name="nama" class="form-control" placeholder="Masukkan nama lengkap" required>
          </div>

          <div class="mb-3">
            <label>Password <span class="text-danger">*</span></label>
            <input type="password" name="password" class="form-control" placeholder="Minimal 6 karakter" required>
            <small class="text-muted">Password akan di-hash otomatis.</small>
          </div>

          {{-- PASANGAN MAPEL + KELAS --}}
          <div class="mb-1">
            <label>Mata Pelajaran & Kelas yang Diajar <span class="text-danger">*</span></label>
            <small class="text-muted d-block mb-2">Tambahkan baris untuk setiap kombinasi mapel & kelas.</small>
          </div>

          <div id="tambahRows">
            {{-- Baris pertama default --}}
            <div class="mengajar-row">
                <span class="row-label">Mapel</span>
                <select name="id_mapel[]" required>
                    <option value="">-- Pilih Mapel --</option>
                    @foreach($mapels as $mapel)
                        <option value="{{ $mapel->id_mapel }}">{{ $mapel->nama_mapel }}</option>
                    @endforeach
                </select>
                <span class="row-label">Kelas</span>
                <select name="id_kelas[]" required>
                    <option value="">-- Pilih Kelas --</option>
                    @foreach($kelas as $k)
                        <option value="{{ $k->id_kelas }}">{{ $k->tingkat }} {{ $k->nama_kelas }}</option>
                    @endforeach
                </select>
                <button type="button" class="btn-hapus-row" onclick="hapusRow(this)" title="Hapus baris">✕</button>
            </div>
          </div>

          <button type="button" class="btn-tambah-row" onclick="tambahRow('tambahRows')">
            + Tambah Mapel/Kelas
          </button>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-success">Simpan Data</button>
        </div>
      </form>
    </div>
  </div>
</div>


{{-- ============================================================ --}}
{{-- MODAL EDIT DATA                                              --}}
{{-- ============================================================ --}}
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header modal-header-pastel">
        <h5 class="modal-title">Edit Data Guru</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <form id="formEdit" method="POST">
        @csrf
        @method('PUT')

        <div class="modal-body">

          <div class="mb-3">
            <label>NIP <span class="text-danger">*</span></label>
            <input type="text" name="nip" id="editNip" class="form-control" required>
          </div>

          <div class="mb-3">
            <label>Nama Lengkap <span class="text-danger">*</span></label>
            <input type="text" name="nama" id="editNama" class="form-control" required>
          </div>

          <div class="mb-3">
            <label>Password Baru <small class="text-muted fw-normal">(Kosongkan jika tidak ingin mengubah)</small></label>
            <input type="password" name="password" class="form-control" placeholder="Minimal 6 karakter">
          </div>

          {{-- PASANGAN MAPEL + KELAS --}}
          <div class="mb-1">
            <label>Mata Pelajaran & Kelas yang Diajar <span class="text-danger">*</span></label>
            <small class="text-muted d-block mb-2">Tambahkan baris untuk setiap kombinasi mapel & kelas.</small>
          </div>

          <div id="editRows">
            {{-- Diisi oleh JavaScript --}}
          </div>

          <button type="button" class="btn-tambah-row" onclick="tambahRow('editRows')">
            + Tambah Mapel/Kelas
          </button>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-warning">Update Data</button>
        </div>
      </form>

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


{{-- ============================================================ --}}
{{-- TEMPLATE ROW — kelas auto-fill via AJAX saat mapel dipilih  --}}
{{-- ============================================================ --}}
<template id="rowTemplate">
    <div class="mengajar-row">
        <span class="row-label">Mapel</span>
        <select name="id_mapel[]" class="select-mapel" onchange="onMapelChange(this)" required>
            <option value="">-- Pilih Mapel --</option>
            @foreach($mapels as $mapel)
                <option value="{{ $mapel->id_mapel }}">{{ $mapel->nama_mapel }}</option>
            @endforeach
        </select>
        <span class="row-label">Kelas</span>
        <select name="id_kelas[]" class="select-kelas" required disabled>
            <option value="">-- Pilih mapel dulu --</option>
        </select>
        <button type="button" class="btn-hapus-row" onclick="hapusRow(this)" title="Hapus baris">✕</button>
    </div>
</template>


<script>
const KELAS_BY_MAPEL_URL = "{{ route('admin.guru.kelasByMapel') }}";

// ===== SAAT MAPEL DIPILIH → fetch kelas otomatis =====
async function onMapelChange(selectMapel) {
    const idMapel    = selectMapel.value;
    const row        = selectMapel.closest('.mengajar-row');
    const selectKelas = row.querySelector('.select-kelas');

    // Reset kelas
    selectKelas.innerHTML = '<option value="">-- Memuat kelas... --</option>';
    selectKelas.disabled  = true;

    if (!idMapel) {
        selectKelas.innerHTML = '<option value="">-- Pilih mapel dulu --</option>';
        return;
    }

    try {
        const res  = await fetch(`${KELAS_BY_MAPEL_URL}?id_mapel=${idMapel}`);
        const data = await res.json();

        if (data.length === 0) {
            selectKelas.innerHTML = '<option value="">Tidak ada kelas untuk mapel ini</option>';
            return;
        }

        selectKelas.innerHTML = '<option value="">-- Pilih Kelas --</option>';
        data.forEach(k => {
            const opt = document.createElement('option');
            opt.value       = k.id_kelas;
            opt.textContent = k.tingkat + ' ' + k.nama_kelas;
            selectKelas.appendChild(opt);
        });

        // Jika hanya 1 kelas, langsung pilih otomatis
        if (data.length === 1) {
            selectKelas.value = data[0].id_kelas;
        }

        selectKelas.disabled = false;

    } catch (e) {
        selectKelas.innerHTML = '<option value="">Gagal memuat kelas</option>';
    }
}

// ===== TAMBAH BARIS BARU =====
async function tambahRow(containerId, selectedMapel = null, selectedKelas = null) {
    const template  = document.getElementById('rowTemplate');
    const clone     = template.content.cloneNode(true);
    const container = document.getElementById(containerId);

    container.appendChild(clone);

    const rows = container.querySelectorAll('.mengajar-row');
    const last = rows[rows.length - 1];
    const selectMapel = last.querySelector('.select-mapel');
    const selectKelas = last.querySelector('.select-kelas');

    if (selectedMapel) {
        selectMapel.value = selectedMapel;

        // Fetch kelas untuk mapel yang sudah dipilih
        try {
            const res  = await fetch(`${KELAS_BY_MAPEL_URL}?id_mapel=${selectedMapel}`);
            const data = await res.json();

            selectKelas.innerHTML = '<option value="">-- Pilih Kelas --</option>';
            data.forEach(k => {
                const opt = document.createElement('option');
                opt.value       = k.id_kelas;
                opt.textContent = k.tingkat + ' ' + k.nama_kelas;
                selectKelas.appendChild(opt);
            });

            if (selectedKelas) selectKelas.value = selectedKelas;
            selectKelas.disabled = false;

        } catch (e) {
            selectKelas.innerHTML = '<option value="">Gagal memuat kelas</option>';
        }
    }
}

// ===== HAPUS BARIS =====
function hapusRow(btn) {
    const container = btn.closest('[id$="Rows"]');
    const rows = container.querySelectorAll('.mengajar-row');
    if (rows.length <= 1) {
        alert('Minimal harus ada 1 mata pelajaran.');
        return;
    }
    btn.closest('.mengajar-row').remove();
}

// ===== BUKA MODAL EDIT =====
async function openEditModal(idGuru, nip, nama, mengajars) {
    document.getElementById('formEdit').action = "{{ url('admin/guru') }}/" + idGuru;
    document.getElementById('editNip').value   = nip;
    document.getElementById('editNama').value  = nama;

    const editRows = document.getElementById('editRows');
    editRows.innerHTML = '';

    if (mengajars && mengajars.length > 0) {
        for (const m of mengajars) {
            await tambahRow('editRows', m.id_mapel, m.id_kelas);
        }
    } else {
        tambahRow('editRows');
    }

    new bootstrap.Modal(document.getElementById('modalEdit')).show();
}
</script>

@endsection