@extends('guru.layouts.app')

@section('title', 'Daftar Mata Pelajaran')

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

.table-header {
    background: #a5e6ba;
}

.action-btn {
    padding: 6px 14px;
    border-radius: 10px;
    border: none;
    font-size: 13px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-materi {
    background: #2b8ef3;
    color: white;
}

.btn-materi:hover { background: #1a7ae0; color: white; }

.btn-tugas {
    background: #f97316;
    color: white;
}

.btn-tugas:hover { background: #ea6c0a; color: white; }

.kelas-badge {
    display: inline-block;
    background: #e6f0ff;
    color: #1d4ed8;
    font-size: 12px;
    font-weight: 600;
    padding: 3px 10px;
    border-radius: 99px;
    margin: 2px;
}

/* MODAL */
.modal-header-blue {
    background: #2b8ef3;
    color: white;
    border-bottom: none;
    border-radius: 16px 16px 0 0;
}

.modal-header-orange {
    background: #f97316;
    color: white;
    border-bottom: none;
    border-radius: 16px 16px 0 0;
}

.modal-header-blue .btn-close,
.modal-header-orange .btn-close {
    filter: brightness(0) invert(1);
}

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

.modal-body label { font-weight: 600; font-size: 14px; }

.upload-area {
    border: 2px dashed #cbd5e1;
    border-radius: 12px;
    padding: 24px;
    text-align: center;
    cursor: pointer;
    position: relative;
    transition: border-color 0.2s, background 0.2s;
}

.upload-area:hover { border-color: #2b8ef3; background: #f0f7ff; }

.upload-area input[type="file"] {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
    width: 100%;
    height: 100%;
}

.file-preview {
    display: none;
    align-items: center;
    gap: 10px;
    background: #f0f7ff;
    border-radius: 8px;
    padding: 10px 14px;
    margin-top: 10px;
    font-size: 13px;
    font-weight: 600;
    color: #1e293b;
}

.file-preview.show { display: flex; }

.btn-history-materi {
    background: #8b5cf6;
    color: white;
}
.btn-history-materi:hover { background: #7c3aed; color: white; }

.btn-history-tugas {
    background: #14b8a6;
    color: white;
}
.btn-history-tugas:hover { background: #0d9488; color: white; }
    background: #dcfce7;
    color: #166534;
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 14px;
}

.alert-error-custom {
    background: #fee2e2;
    color: #991b1b;
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 14px;
}
</style>
@endpush

@section('content')

<h3 class="page-title">MATA PELAJARAN YANG ANDA AJAR</h3>

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

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

<div class="custom-card">
    <table class="table text-center align-middle">
        <thead class="table-header">
            <tr>
                <th>No</th>
                <th>Nama Mata Pelajaran</th>
                <th>Kelas yang Diajar</th>
                <th>Aksi</th>
            </tr>
        </thead>

        <tbody>
            @forelse($mengajars as $idMapel => $rows)
            @php
                $mapel    = $rows->first()->mapel;
                $kelasList = $rows->map(fn($m) => $m->kelas)->filter();
                // Ambil id_mengajar pertama sebagai default (bisa dipilih per kelas di modal)
                $mengajarOptions = $rows->map(fn($m) => [
                    'id_mengajar' => $m->id_mengajar,
                    'kelas'       => optional($m->kelas)->tingkat . ' ' . optional($m->kelas)->nama_kelas,
                ]);
            @endphp
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ optional($mapel)->nama_mapel ?? '-' }}</td>

                {{-- KOLOM KELAS --}}
                <td>
                    @foreach($kelasList as $kelas)
                        <span class="kelas-badge">
                            {{ $kelas->tingkat }} {{ $kelas->nama_kelas }}
                        </span>
                    @endforeach
                </td>

                {{-- AKSI --}}
                <td>
                    <div class="d-flex flex-wrap gap-1 justify-content-center">
                        <button class="action-btn btn-materi"
                            onclick="openMateriModal(
                                '{{ addslashes(optional($mapel)->nama_mapel) }}',
                                {{ $mengajarOptions->toJson() }}
                            )">
                            📄 Upload Materi
                        </button>

                        <button class="action-btn btn-tugas"
                            onclick="openTugasModal(
                                '{{ addslashes(optional($mapel)->nama_mapel) }}',
                                {{ $mengajarOptions->toJson() }}
                            )">
                            📋 Buat Tugas
                        </button>

                        <a href="{{ route('guru.materi.history', ['id_mapel' => $idMapel]) }}"
                           class="action-btn btn-history-materi">
                            🗂️ History Materi
                        </a>

                        <a href="{{ route('guru.tugas.history', ['id_mapel' => $idMapel]) }}"
                           class="action-btn btn-history-tugas">
                            📑 History Tugas
                        </a>
                    </div>
                </td>
            </tr>
            @empty
            <tr>
                <td colspan="4" class="text-muted py-4">
                    Anda belum mengajar mata pelajaran apapun.
                </td>
            </tr>
            @endforelse
        </tbody>
    </table>
</div>


{{-- ============================================================ --}}
{{-- MODAL UPLOAD MATERI                                          --}}
{{-- ============================================================ --}}
<div class="modal fade" id="modalMateri" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header modal-header-blue">
        <h5 class="modal-title">📄 Upload Materi — <span id="materiMapelLabel"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

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

          {{-- Pilih Kelas (jika guru ajar mapel ini di lebih dari 1 kelas) --}}
          <div class="mb-3">
            <label>Kelas Tujuan <span class="text-danger">*</span></label>
            <select name="id_mengajar" id="materiMengajar" class="form-control" required>
                <option value="">-- Pilih Kelas --</option>
            </select>
            <small class="text-muted">Materi akan dikirim ke kelas yang dipilih.</small>
          </div>

          <div class="mb-3">
            <label>Judul Materi <span class="text-danger">*</span></label>
            <input type="text" name="judul_materi" class="form-control"
                   placeholder="Contoh: Pertemuan 1 - Pengantar Algoritma" required>
          </div>

          <div class="mb-3">
            <label>Deskripsi</label>
            <textarea name="deskripsi" class="form-control" rows="3"
                      placeholder="Deskripsi singkat materi (opsional)"></textarea>
          </div>

          <div class="mb-3">
            <label>File Materi <small class="text-muted fw-normal">(PDF, DOC, PPT, JPG — maks 10MB)</small></label>
            <div class="upload-area" id="materiUploadArea">
                <input type="file" name="lampiran_materi" id="materiFile"
                       accept=".pdf,.doc,.docx,.ppt,.pptx,.jpg,.jpeg,.png"
                       onchange="previewFile(this, 'materiPreview', 'materiFileName')">
                <div style="font-size:32px">☁️</div>
                <p style="margin:6px 0 0;font-size:14px;color:#64748b">
                    <strong>Klik</strong> atau drag file ke sini
                </p>
            </div>
            <div class="file-preview" id="materiPreview">
                📎 <span id="materiFileName">-</span>
            </div>
          </div>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-primary">Upload Materi</button>
        </div>
      </form>
    </div>
  </div>
</div>


{{-- ============================================================ --}}
{{-- MODAL BUAT TUGAS                                             --}}
{{-- ============================================================ --}}
<div class="modal fade" id="modalTugas" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header modal-header-orange">
        <h5 class="modal-title">📋 Buat Tugas — <span id="tugasMapelLabel"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

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

          {{-- Pilih Kelas --}}
          <div class="mb-3">
            <label>Kelas Tujuan <span class="text-danger">*</span></label>
            <select name="id_mengajar" id="tugasMengajar" class="form-control" required>
                <option value="">-- Pilih Kelas --</option>
            </select>
            <small class="text-muted">Tugas akan dikirim ke kelas yang dipilih.</small>
          </div>

          <div class="mb-3">
            <label>Judul Tugas <span class="text-danger">*</span></label>
            <input type="text" name="judul_tugas" class="form-control"
                   placeholder="Contoh: Latihan Soal Bab 3" required>
          </div>

          <div class="mb-3">
            <label>Keterangan / Instruksi</label>
            <textarea name="keterangan" class="form-control" rows="4"
                      placeholder="Instruksi pengerjaan tugas (opsional)"></textarea>
          </div>

          <div class="mb-3">
            <label>Deadline <span class="text-danger">*</span></label>
            <input type="datetime-local" name="deadline" class="form-control" required
                   min="{{ now()->format('Y-m-d\TH:i') }}">
            <small class="text-muted">Pastikan deadline lebih dari waktu sekarang.</small>
          </div>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn" style="background:#f97316;color:white">Buat Tugas</button>
        </div>
      </form>
    </div>
  </div>
</div>

@endsection

@push('scripts')
<script>
// ===== BUKA MODAL MATERI =====
function openMateriModal(namaMapel, mengajars) {
    document.getElementById('materiMapelLabel').textContent = namaMapel;

    const select = document.getElementById('materiMengajar');
    select.innerHTML = '<option value="">-- Pilih Kelas --</option>';

    mengajars.forEach(m => {
        const opt = document.createElement('option');
        opt.value       = m.id_mengajar;
        opt.textContent = m.kelas;
        select.appendChild(opt);
    });

    // Jika hanya 1 kelas, langsung pilih otomatis
    if (mengajars.length === 1) select.value = mengajars[0].id_mengajar;

    // Reset form
    document.querySelector('#modalMateri input[name="judul_materi"]').value = '';
    document.querySelector('#modalMateri textarea[name="deskripsi"]').value  = '';
    document.getElementById('materiPreview').classList.remove('show');

    new bootstrap.Modal(document.getElementById('modalMateri')).show();
}

// ===== BUKA MODAL TUGAS =====
function openTugasModal(namaMapel, mengajars) {
    document.getElementById('tugasMapelLabel').textContent = namaMapel;

    const select = document.getElementById('tugasMengajar');
    select.innerHTML = '<option value="">-- Pilih Kelas --</option>';

    mengajars.forEach(m => {
        const opt = document.createElement('option');
        opt.value       = m.id_mengajar;
        opt.textContent = m.kelas;
        select.appendChild(opt);
    });

    if (mengajars.length === 1) select.value = mengajars[0].id_mengajar;

    // Reset form
    document.querySelector('#modalTugas input[name="judul_tugas"]').value   = '';
    document.querySelector('#modalTugas textarea[name="keterangan"]').value  = '';
    document.querySelector('#modalTugas input[name="deadline"]').value       = '';

    new bootstrap.Modal(document.getElementById('modalTugas')).show();
}

// ===== PREVIEW FILE =====
function previewFile(input, previewId, nameId) {
    const preview = document.getElementById(previewId);
    const nameEl  = document.getElementById(nameId);
    if (input.files && input.files[0]) {
        nameEl.textContent = input.files[0].name + 
            ' (' + (input.files[0].size / 1024 / 1024).toFixed(2) + ' MB)';
        preview.classList.add('show');
    }
}
</script>
@endpush