@extends('guru.layouts.app')

@section('title', 'History Materi')

@push('styles')
<style>
.page-title {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 6px;
    margin-top: -20px;
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.back-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #2b8ef3;
    font-weight: 600;
    font-size: 14px;
    text-decoration: none;
    margin-bottom: 20px;
}

.back-link:hover { text-decoration: underline; }

.custom-card {
    background: white;
    border-radius: 20px;
    border: 2px solid #e5e5e5;
    padding: 20px;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.table-header { background: #a5e6ba; }

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

.kelas-badge {
    display: inline-block;
    background: #f0fdf4;
    color: #166534;
    font-size: 12px;
    font-weight: 600;
    padding: 3px 10px;
    border-radius: 99px;
    white-space: nowrap;
}

.btn-unduh {
    background: #e6f0ff;
    color: #2b8ef3;
    border: none;
    border-radius: 8px;
    padding: 5px 12px;
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    transition: background 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    white-space: nowrap;
}

.btn-unduh:hover { background: #bfdbfe; color: #1d4ed8; }

.btn-edit-tbl {
    background: #fef9c3;
    color: #854d0e;
    border: none;
    border-radius: 8px;
    padding: 5px 12px;
    font-size: 13px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    white-space: nowrap;
    cursor: pointer;
    transition: background 0.2s;
}
.btn-edit-tbl:hover { background: #fde047; color: #713f12; }

.alert-success-custom {
    background: #dcfce7;
    color: #166534;
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.empty-state {
    text-align: center;
    padding: 50px 20px;
    color: #94a3b8;
}

.table { min-width: 600px; }

/* ===== MODAL STYLE (selaras dengan daftar-siswa) ===== */
.modal-content {
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    border: none;
}

.modal-header-pastel-yellow {
    background: #FFD97D !important;
    color: black !important;
    border-bottom: none;
    padding: 15px 20px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
}

.modal-header-pastel-yellow .modal-title {
    font-weight: 700;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.modal-body .form-label-custom {
    font-size: 13px;
    font-weight: 700;
    color: #475569;
    margin-bottom: 5px;
    display: block;
}

.modal-body .form-control {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s;
}

.modal-body .form-control:focus {
    border-color: #2b8ef3;
    box-shadow: 0 0 0 3px rgba(43,142,243,0.12);
}

.file-chip-modal {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #eff6ff;
    color: #1d4ed8;
    border-radius: 8px;
    padding: 5px 10px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 8px;
}

.file-hint-modal {
    font-size: 11px;
    color: #94a3b8;
    margin-top: 4px;
}

.inline-icon { width: 16px; height: 16px; vertical-align: middle; display: inline-block; }

.btn-green {
    background: #16a34a; color: white; border: none; border-radius: 10px;
    padding: 8px 18px; font-size: 13px; font-weight: 700;
    cursor: pointer; font-family: 'Poppins', sans-serif;
    display: inline-flex; align-items: center; gap: 6px; transition: background 0.2s;
}

@media (max-width: 576px) {
    .page-title { font-size: 18px; margin-top: 0; }
    .custom-card { padding: 12px; border-radius: 14px; }
}
</style>
@endpush

@section('content')

<a href="{{ route('guru.mapel.index') }}" class="back-link">← Kembali ke Mata Pelajaran</a>

<h3 class="page-title">
    <img src="{{ asset('images/icon/gurud/file.png') }}" class="icon-inline" alt="Ikon file">
    HISTORY MATERI
</h3>

@if(session('success'))
    <div class="alert-success-custom">
        <img src="{{ asset('images/icon/gurud/v.png') }}" class="icon-inline" alt="Berhasil">
        {{ session('success') }}
    </div>
@endif

<div class="custom-card">
    @if($materiList->isEmpty())
        <div class="empty-state">
            <div style="margin-bottom:12px">
                <img src="{{ asset('images/icon/gurud/mailbox.png') }}" class="icon-lg" alt="Belum ada materi">
            </div>
            <p>Belum ada materi yang diupload.</p>
        </div>
    @else
        <table class="table align-middle">
            <thead class="table-header text-center">
                <tr>
                    <th>No</th>
                    <th>Judul Materi</th>
                    <th>Mata Pelajaran</th>
                    <th>Kelas</th>
                    <th>Tanggal Upload</th>
                    <th>File</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                @foreach($materiList as $i => $materi)
                <tr>
                    <td class="text-center">{{ $materiList->firstItem() + $i }}</td>
                    <td>
                        <div style="font-weight:600;color:#1e293b;word-break:break-word;max-width:180px;">{{ $materi->judul_materi }}</div>
                        @if($materi->deskripsi)
                            <div style="font-size:12px;color:#94a3b8;margin-top:2px">
                                {{ Str::limit($materi->deskripsi, 60) }}
                            </div>
                        @endif
                    </td>
                    <td class="text-center">
                        <span class="mapel-badge">
                            {{ optional(optional($materi->mengajar)->mapel)->nama_mapel ?? '-' }}
                        </span>
                    </td>
                    <td class="text-center">
                        <span class="kelas-badge">
                            {{ optional(optional($materi->mengajar)->kelas)->tingkat }}
                            {{ optional(optional($materi->mengajar)->kelas)->nama_kelas ?? '-' }}
                        </span>
                    </td>
                    <td class="text-center" style="font-size:13px;color:#64748b;white-space:nowrap;">
                        {{ \Carbon\Carbon::parse($materi->tanggal_upload)->format('d M Y, H:i') }}
                    </td>
                    <td class="text-center">
                        @if($materi->lampiran_materi)
                            @php
                                $ext = strtolower(pathinfo($materi->lampiran_materi, PATHINFO_EXTENSION));
                                $iconSrc = match(true) {
                                    in_array($ext, ['pdf'])               => asset('images/icon/gurud/file2.png'),
                                    in_array($ext, ['doc','docx'])        => asset('images/icon/gurud/buku1.png'),
                                    in_array($ext, ['ppt','pptx'])        => asset('images/icon/gurud/lb.png'),
                                    in_array($ext, ['jpg','jpeg','png'])  => asset('images/icon/gurud/image.png'),
                                    default                               => asset('images/icon/gurud/link.png'),
                                };
                                $iconAlt = match(true) {
                                    in_array($ext, ['pdf'])               => 'File PDF',
                                    in_array($ext, ['doc','docx'])        => 'File Word',
                                    in_array($ext, ['ppt','pptx'])        => 'File PowerPoint',
                                    in_array($ext, ['jpg','jpeg','png'])  => 'File gambar',
                                    default                               => 'File lampiran',
                                };
                            @endphp
                            <a href="{{ url('storage/app/public/' . $materi->lampiran_materi) }}"
                               target="_blank" class="btn-unduh">
                                <img src="{{ $iconSrc }}" class="icon-inline" alt="{{ $iconAlt }}"> Unduh
                            </a>
                        @else
                            <span style="font-size:12px;color:#94a3b8">Tidak ada file</span>
                        @endif
                    </td>
                    <td class="text-center">
                        <button
                            type="button"
                            class="btn-edit-tbl"
                            onclick="openEditMateri(
                                {{ $materi->id_materi }},
                                '{{ addslashes($materi->judul_materi) }}',
                                '{{ addslashes($materi->deskripsi ?? '') }}',
                                '{{ $materi->lampiran_materi ?? '' }}'
                            )">
                            <img src="{{ asset('images/icon/main/edit.png') }}" class="icon-inline" alt="Edit">
                            Edit
                        </button>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>

        <div class="d-flex justify-content-end mt-3">
            {{ $materiList->links() }}
        </div>
    @endif
</div>


{{-- ===== MODAL EDIT MATERI ===== --}}
<div class="modal fade" id="modalEditMateri" tabindex="-1" aria-labelledby="modalEditMateriLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">

            <div class="modal-header modal-header-pastel-yellow">
                <h5 class="modal-title" id="modalEditMateriLabel">
                    <img src="{{ asset('images/icon/main/edit.png') }}" width="18" alt="Edit">
                    Edit Materi
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>

            <form id="formEditMateri" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')

                <div class="modal-body">

                    <div class="mb-3">
                        <label class="form-label-custom">
                            Judul Materi <span class="text-danger">*</span>
                        </label>
                        <input type="text"
                               id="editMateriJudul"
                               name="judul_materi"
                               class="form-control"
                               required
                               placeholder="Masukkan judul materi">
                    </div>

                    <div class="mb-3">
                        <label class="form-label-custom">Deskripsi</label>
                        <textarea id="editMateriDeskripsi"
                                  name="deskripsi"
                                  class="form-control"
                                  rows="3"
                                  style="resize:vertical;"
                                  placeholder="Deskripsi singkat materi (opsional)"></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label-custom">Ganti File Lampiran</label>
                        <div id="editMateriFileChip"></div>
                        <input type="file"
                               id="editMateriFile"
                               name="lampiran_materi"
                               class="form-control"
                               accept=".pdf,.doc,.docx,.ppt,.pptx,.jpg,.jpeg,.png">
                        <div class="file-hint-modal">Kosongkan jika tidak ingin mengganti file yang sudah ada.</div>
                    </div>

                </div>

                <div class="modal-footer" style="border-top: 2px solid #f1f5f9;">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-green" id="tambah-btn-submit">
                        <img src="{{ asset('images/icon/gurud/save.png') }}" class="inline-icon" alt=""> Simpan
                    </button>
                </div>
            </form>

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


@push('scripts')
<script>
function openEditMateri(id, judul, deskripsi, lampiran) {
    // Set action form ke route update materi
    document.getElementById('formEditMateri').action = "{{ url('guru/materi') }}/" + id;

    // Isi field
    document.getElementById('editMateriJudul').value    = judul;
    document.getElementById('editMateriDeskripsi').value = deskripsi;

    // Tampilkan chip nama file lama
    const chip = document.getElementById('editMateriFileChip');
    if (lampiran) {
        const filename = lampiran.split('/').pop();
        chip.innerHTML = `<div class="file-chip-modal">📄 ${filename}</div>`;
    } else {
        chip.innerHTML = '';
    }

    // Reset input file agar tidak ngirim file lama
    document.getElementById('editMateriFile').value = '';

    // Buka modal Bootstrap
    new bootstrap.Modal(document.getElementById('modalEditMateri')).show();
}
</script>

{{-- Re-open modal edit jika validasi gagal --}}
@if($errors->any() && session('error_from') == 'edit_materi' && session('edit_materi'))
<script>
document.addEventListener('DOMContentLoaded', function () {
    @php $em = session('edit_materi'); @endphp
    document.getElementById('formEditMateri').action    = "{{ url('guru/materi') }}/{{ $em['id_materi'] }}";
    document.getElementById('editMateriJudul').value    = '{{ addslashes($em['judul_materi']) }}';
    document.getElementById('editMateriDeskripsi').value = '{{ addslashes($em['deskripsi'] ?? '') }}';
    new bootstrap.Modal(document.getElementById('modalEditMateri')).show();
});
</script>
@endif
@endpush

@endsection