@extends('guru.kelas.layout')

@php
    $selectedMapel = $selectedMapel ?? null;
    $materiRoute = $selectedMapel
        ? route('guru.kelas.mapel.materi', [$kelas->id, $selectedMapel->id])
        : route('guru.kelas.materi', $kelas->id);
@endphp

@section('tab_content')
<div class="main-grid" style="grid-template-columns: 1fr; align-items: start;">
    <div class="card">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; border-bottom: 1px solid #cbd5e1; padding-bottom: 16px; margin-bottom: 20px;">
            <h3 style="margin: 0; font-size: 1.25rem; font-weight: 700; color: #1e293b;"><i class="fa-solid fa-book-open text-primary"></i> Daftar Materi {{ $selectedMapel ? 'Kelas ' . $kelas->nama_kelas . ' - ' . $selectedMapel->nama_mapel : 'Kelas ' . $kelas->nama_kelas }}</h3>
            <button type="button" class="btn btn-primary" onclick="openUploadModal()" style="height: 40px; padding: 0 18px; font-weight: 600; border-radius: 8px; border: none; cursor: pointer; background-color: #2563eb; color: #fff; display: inline-flex; align-items: center; gap: 8px;">
                <i class="fa-solid fa-cloud-arrow-up"></i> Upload Materi
            </button>
        </div>
        
        <div class="card-body">
            <!-- Search & Filters Toolbar -->
            <div style="display: flex; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; align-items: center;">
                <form action="{{ $materiRoute }}" method="GET" style="display: flex; gap: 12px; flex-wrap: wrap; width: 100%;">
                    <input 
                        type="text" 
                        name="search" 
                        value="{{ request('search') }}" 
                        class="form-control" 
                        placeholder="Cari judul materi..." 
                        style="min-width: 280px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 42px;"
                    >
                    <select 
                        name="filter_status" 
                        class="form-control" 
                        onchange="this.form.submit()" 
                        style="min-width: 150px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 42px;"
                    >
                        <option value="">Semua Status</option>
                        <option value="aktif" {{ request('filter_status') === 'aktif' ? 'selected' : '' }}>Aktif</option>
                        <option value="draft" {{ request('filter_status') === 'draft' ? 'selected' : '' }}>Draft</option>
                    </select>
                    <button type="submit" class="btn btn-primary" style="height: 42px; padding: 0 16px; font-weight: 600; border-radius: 6px; border: none; cursor: pointer; background: #2563eb; color: #fff;">Cari</button>
                    @if(request('search') || request('filter_status'))
                        <a href="{{ $materiRoute }}" class="btn btn-outline" style="height: 42px; display: inline-flex; align-items: center; justify-content: center; padding: 0 16px; font-weight: 600; border-radius: 6px; border: 1px solid #cbd5e1; text-decoration: none; color: #475569; background: #fff;">Reset</a>
                    @endif
                </form>
            </div>

            <!-- Materials Table -->
            <div class="table-responsive" style="overflow-x: auto; width: 100%;">
                <table class="modern-table" style="width: 100%; border-collapse: collapse; text-align: left;">
                    <thead>
                        <tr style="border-bottom: 2px solid #e2e8f0; background-color: #f8fafc;">
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">No</th>
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">Judul</th>
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">Mata Pelajaran</th>
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">File</th>
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">Status</th>
                            <th style="padding: 12px 16px; font-weight: 700; color: #475569; font-size: 0.85rem; text-transform: uppercase;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($materiList as $m)
                            <tr style="border-bottom: 1px solid #e2e8f0; transition: background 0.15s ease;">
                                <td style="padding: 14px 16px; color: #475569;">{{ ($materiList->currentPage() - 1) * $materiList->perPage() + $loop->iteration }}</td>
                                <td style="padding: 14px 16px;">
                                    <div style="font-weight: 600; color: #0f172a;">{{ $m->judul }}</div>
                                    @if($m->deskripsi)
                                        <div style="font-size: 0.82rem; color: #64748b; margin-top: 2px; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ $m->deskripsi }}</div>
                                    @endif
                                </td>
                                <td style="padding: 14px 16px; font-weight: 500; color: #334155;">{{ $m->mataPelajaran->nama_mapel }}</td>
                                <td style="padding: 14px 16px;">
                                    <div style="display: flex; align-items: center; gap: 8px;">
                                        @if($m->tipe_file === 'pdf')
                                            <i class="fa-solid fa-file-pdf" style="color: #ef4444; font-size: 1.25rem;"></i>
                                        @elseif($m->tipe_file === 'image')
                                            <i class="fa-solid fa-file-image" style="color: #10b981; font-size: 1.25rem;"></i>
                                        @else
                                            <i class="fa-solid fa-file-powerpoint" style="color: #f59e0b; font-size: 1.25rem;"></i>
                                        @endif
                                        <span style="font-size: 0.88rem; font-weight: 500; color: #1e293b;">{{ $m->nama_file }}</span>
                                    </div>
                                    <div style="font-size: 0.78rem; color: #64748b; margin-top: 2px;">{{ round($m->ukuran_file / 1024, 1) }} KB</div>
                                </td>
                                <td style="padding: 14px 16px;">
                                    @if($m->status === 'aktif')
                                        <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 9999px; font-size: 0.78rem; font-weight: 600; background-color: #d1e7dd; color: #0f5132;"><i class="fa-solid fa-circle-check"></i> Aktif</span>
                                    @else
                                        <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 9999px; font-size: 0.78rem; font-weight: 600; background-color: #f8d7da; color: #842029;"><i class="fa-solid fa-circle-notch"></i> Draft</span>
                                    @endif
                                </td>
                                <td style="padding: 14px 16px;">
                                    <div style="display: flex; align-items: center; gap: 8px;">
                                        <a href="{{ route('guru.materi.download', $m->id) }}" class="btn-sm btn-outline" title="Download" style="text-decoration: none; border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px; color: #475569; display: inline-flex; justify-content: center; align-items: center; background: #fff; width: 32px; height: 32px;"><i class="fa-solid fa-download"></i></a>
                                        <button onclick="previewFile('{{ $m->id }}', '{{ $m->judul }}', '{{ $m->tipe_file }}', '{{ route('materi.preview', $m->id) }}')" class="btn-sm btn-outline" title="Preview" style="border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px; color: #475569; display: inline-flex; justify-content: center; align-items: center; background: #fff; width: 32px; height: 32px; cursor: pointer;"><i class="fa-solid fa-eye"></i></button>
                                        <button onclick="openEditModal('{{ $m->id }}')" class="btn-sm btn-outline" title="Edit" style="border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px; color: #475569; display: inline-flex; justify-content: center; align-items: center; background: #fff; width: 32px; height: 32px; cursor: pointer;"><i class="fa-solid fa-edit"></i></button>
                                        <button onclick="openSalinModal('{{ $m->id }}', '{{ $m->judul }}')" class="btn-sm btn-outline" title="Salin ke Kelas Lain" style="border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px; color: #2563eb; display: inline-flex; justify-content: center; align-items: center; background: #fff; width: 32px; height: 32px; cursor: pointer;"><i class="fa-solid fa-copy"></i></button>
                                        
                                        <form action="{{ route('guru.materi.destroy', $m->id) }}" method="POST" onsubmit="return confirm('Apakah Anda yakin ingin menghapus materi ini?')" style="margin: 0; display: inline;">
                                            @csrf
                                            @method('DELETE')
                                            @if($selectedMapel)
                                                <input type="hidden" name="redirect_mapel_id" value="{{ $selectedMapel->id }}">
                                            @endif
                                            <button type="submit" class="btn-sm btn-outline" title="Hapus" style="border: 1px solid #fca5a5; border-radius: 6px; padding: 6px; color: #dc2626; display: inline-flex; justify-content: center; align-items: center; background: #fff; width: 32px; height: 32px; cursor: pointer;"><i class="fa-solid fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" style="padding: 24px; text-align: center; color: #64748b;">Belum ada materi untuk kelas ini. Klik tombol "Upload Materi" untuk menambahkan.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <!-- Custom Pagination Links -->
            <div style="margin-top: 20px;">
                {{ $materiList->links('vendor.pagination.custom') }}
            </div>
        </div>
    </div>
</div>

<!-- UPLOAD MODAL -->
<div class="modal-overlay" id="uploadModal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); z-index: 9999; align-items: center; justify-content: center; padding: 20px;">
    <div class="modal-content" style="background: #fff; border-radius: 12px; width: min(100%, 640px); max-height: 90vh; display: flex; flex-direction: column; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); border: 1px solid #cbd5e1; overflow: hidden; animation: modalIn 0.2s ease-out; margin: auto;">
        <div style="background: #f8fafc; padding: 18px 24px; border-bottom: 1px solid #cbd5e1; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0;">
            <h3 style="margin: 0; font-size: 1.2rem; font-weight: 700; color: #1e293b;"><i class="fa-solid fa-cloud-arrow-up text-primary"></i> Upload Materi Baru</h3>
            <button onclick="closeUploadModal()" style="border: none; background: transparent; font-size: 1.25rem; cursor: pointer; color: #64748b;"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form action="{{ route('guru.materi.store') }}" method="POST" enctype="multipart/form-data" onsubmit="return handleFormSubmit(this)" style="display: flex; flex-direction: column; flex: 1; overflow: hidden; margin: 0;">
            @csrf
            <input type="hidden" name="redirect_kelas_id" value="{{ $kelas->id }}">
            @if($selectedMapel)
                <input type="hidden" name="redirect_mapel_id" value="{{ $selectedMapel->id }}">
            @endif
            
            <div style="padding: 24px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; flex: 1;">
                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Judul Materi <span style="color: #dc2626;">*</span></label>
                    <input type="text" name="judul" required placeholder="Contoh: Bab 1 Perkalian Pecahan" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px; outline: none; transition: border-color 0.2s ease;">
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Mata Pelajaran <span style="color: #dc2626;">*</span></label>
                    <select name="mata_pelajaran_id" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px; outline: none;">
                        @foreach($mataPelajaran as $mp)
                            <option value="{{ $mp->id }}" @selected($selectedMapel?->id === $mp->id)>{{ $mp->nama_mapel }}</option>
                        @endforeach
                    </select>
                </div>

                <!-- Share checkboxes -->
                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 8px;">Bagikan Ke Kelas <span style="color: #dc2626;">*</span></label>
                    <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 10px; background: #f8fafc; padding: 14px; border: 1px solid #cbd5e1; border-radius: 6px;">
                        @foreach($teacherClasses as $tc)
                            <label style="display: inline-flex; align-items: center; gap: 8px; font-weight: 500; font-size: 0.88rem; color: #475569; cursor: pointer;">
                                <input 
                                    type="checkbox" 
                                    @if($tc->id === $kelas->id)
                                        checked disabled
                                    @else
                                        name="kelas_ids[]" 
                                        value="{{ $tc->id }}" 
                                    @endif
                                    style="width: 16px; height: 16px; accent-color: #2563eb;"
                                >
                                <span>Kelas {{ $tc->nama_kelas }}</span>
                            </label>
                        @endforeach
                    </div>
                    <!-- Add a hidden field for the current class in case checkbox is disabled and doesn't submit -->
                    <input type="hidden" name="kelas_ids[]" value="{{ $kelas->id }}">
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Status Materi <span style="color: #dc2626;">*</span></label>
                    <select name="status" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px; outline: none;">
                        <option value="aktif">Aktif (Dapat dilihat siswa)</option>
                        <option value="draft">Draft (Disimpan sebagai draft)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Deskripsi Materi</label>
                    <textarea name="deskripsi" placeholder="Tuliskan petunjuk singkat atau penjelasan materi..." rows="3" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px; outline: none; transition: border-color 0.2s ease;"></textarea>
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Pilih File <span style="color: #dc2626;">*</span></label>
                    <input type="file" name="file" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 10px;">
                    <div style="font-size: 0.78rem; color: #64748b; margin-top: 4px;">* Maksimal 10MB (PDF/Gambar), 20MB (PPT/PPTX).</div>
                </div>
            </div>

            <div style="padding: 16px 24px; background: #f8fafc; border-top: 1px solid #cbd5e1; display: flex; justify-content: flex-end; gap: 12px; flex-shrink: 0;">
                <button type="button" onclick="closeUploadModal()" class="btn btn-outline" style="height: 42px; padding: 0 18px; border-radius: 8px; border: 1px solid #cbd5e1; background: #fff; cursor: pointer; font-weight: 600; color: #475569;">Batal</button>
                <button type="submit" class="btn btn-primary" style="height: 42px; padding: 0 24px; border-radius: 8px; border: none; background: #2563eb; color: #fff; cursor: pointer; font-weight: 600;">Simpan & Bagikan</button>
            </div>
        </form>
    </div>
</div>

<!-- EDIT MODAL -->
<div class="modal-overlay" id="editModal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); z-index: 9999; align-items: center; justify-content: center; padding: 20px;">
    <div class="modal-content" style="background: #fff; border-radius: 12px; width: min(100%, 640px); max-height: 90vh; display: flex; flex-direction: column; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); border: 1px solid #cbd5e1; overflow: hidden; animation: modalIn 0.2s ease-out; margin: auto;">
        <div style="background: #f8fafc; padding: 18px 24px; border-bottom: 1px solid #cbd5e1; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0;">
            <h3 style="margin: 0; font-size: 1.2rem; font-weight: 700; color: #1e293b;"><i class="fa-solid fa-edit text-primary"></i> Edit Materi</h3>
            <button onclick="closeEditModal()" style="border: none; background: transparent; font-size: 1.25rem; cursor: pointer; color: #64748b;"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form id="editForm" action="" method="POST" enctype="multipart/form-data" onsubmit="return handleFormSubmit(this)" style="display: flex; flex-direction: column; flex: 1; overflow: hidden; margin: 0;">
            @csrf
            @method('PUT')
            @if($selectedMapel)
                <input type="hidden" name="redirect_mapel_id" value="{{ $selectedMapel->id }}">
            @endif
            
            <div style="padding: 24px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; flex: 1;">
                <div class="form-group" id="edit_type_wrapper" style="display: none; background: #eff6ff; border: 1px dashed #bfdbfe; border-radius: 6px; padding: 14px;">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #1e3a8a; margin-bottom: 8px;"><i class="fa-solid fa-circle-info"></i> Tipe Pengeditan Materi</label>
                    <div style="display: flex; flex-direction: column; gap: 8px;">
                        <label style="display: inline-flex; align-items: center; gap: 8px; font-weight: 600; font-size: 0.88rem; color: #1e293b; cursor: pointer;">
                            <input type="radio" name="edit_type" value="global" checked style="accent-color: #2563eb;">
                            <span>Edit Materi Global (Berlaku untuk semua kelas)</span>
                        </label>
                        <label style="display: inline-flex; align-items: center; gap: 8px; font-weight: 600; font-size: 0.88rem; color: #1e293b; cursor: pointer;">
                            <input type="radio" name="edit_type" value="local" style="accent-color: #2563eb;">
                            <span>Duplikat Khusus Kelas Ini (Ubah nama untuk kelas ini saja)</span>
                        </label>
                    </div>
                </div>
                <!-- In case it's a single record without shares, fallback edit_type hidden input -->
                <input type="hidden" name="edit_type" id="fallback_edit_type" value="local">

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Judul Materi <span style="color: #dc2626;">*</span></label>
                    <input type="text" name="judul" id="edit_judul" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px;">
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Mata Pelajaran <span style="color: #dc2626;">*</span></label>
                    <select name="mata_pelajaran_id" id="edit_mapel" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px;">
                        @foreach($mataPelajaran as $mp)
                            <option value="{{ $mp->id }}">{{ $mp->nama_mapel }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Status Materi <span style="color: #dc2626;">*</span></label>
                    <select name="status" id="edit_status" required class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px;">
                        <option value="aktif">Aktif (Dapat dilihat siswa)</option>
                        <option value="draft">Draft (Disimpan sebagai draft)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Deskripsi Materi</label>
                    <textarea name="deskripsi" id="edit_deskripsi" rows="3" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 14px;"></textarea>
                </div>

                <div class="form-group">
                    <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 6px;">Ganti File (Opsional)</label>
                    <input type="file" name="file" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 10px;">
                    <div style="font-size: 0.78rem; color: #64748b; margin-top: 4px;" id="current_file_lbl">File aktif: -</div>
                </div>
            </div>

            <div style="padding: 16px 24px; background: #f8fafc; border-top: 1px solid #cbd5e1; display: flex; justify-content: flex-end; gap: 12px; flex-shrink: 0;">
                <button type="button" onclick="closeEditModal()" class="btn btn-outline" style="height: 42px; padding: 0 18px; border-radius: 8px; border: 1px solid #cbd5e1; background: #fff; cursor: pointer; font-weight: 600; color: #475569;">Batal</button>
                <button type="submit" class="btn btn-primary" style="height: 42px; padding: 0 24px; border-radius: 8px; border: none; background: #2563eb; color: #fff; cursor: pointer; font-weight: 600;">Perbarui Materi</button>
            </div>
        </form>
    </div>
</div>

<!-- SALIN MODAL -->
<div class="modal-overlay" id="salinModal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); z-index: 9999; align-items: flex-start; overflow-y: auto; padding: 40px 24px;">
    <div class="modal-content" style="background: #fff; border-radius: 12px; width: min(100%, 500px); margin: auto; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); border: 1px solid #cbd5e1; overflow: hidden; animation: modalIn 0.2s ease-out;">
        <div style="background: #f8fafc; padding: 18px 24px; border-bottom: 1px solid #cbd5e1; display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1e293b;"><i class="fa-solid fa-copy text-primary"></i> Salin Materi ke Kelas Lain</h3>
            <button onclick="closeSalinModal()" style="border: none; background: transparent; font-size: 1.25rem; cursor: pointer; color: #64748b;"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form id="salinForm" action="" method="POST" style="padding: 24px; display: flex; flex-direction: column; gap: 16px;">
            @csrf
            
            <p style="font-size: 0.9rem; color: #475569; margin: 0; line-height: 1.5;">Pilih kelas-kelas lain yang diajar untuk dibagikan materi: <strong id="salin_materi_judul">Materi</strong></p>

            <div class="form-group">
                <label style="display: block; font-weight: 700; font-size: 0.9rem; color: #334155; margin-bottom: 8px;">Pilih Kelas Penerima</label>
                <div style="display: flex; flex-direction: column; gap: 10px; background: #f8fafc; padding: 14px; border: 1px solid #cbd5e1; border-radius: 6px;">
                    @php
                        $otherClasses = $teacherClasses->filter(fn($tc) => $tc->id !== $kelas->id);
                    @endphp
                    @forelse($otherClasses as $oc)
                        <label style="display: inline-flex; align-items: center; gap: 8px; font-weight: 500; font-size: 0.88rem; color: #475569; cursor: pointer;">
                            <input type="checkbox" name="target_kelas_ids[]" value="{{ $oc->id }}" style="width: 16px; height: 16px; accent-color: #2563eb;">
                            <span>Kelas {{ $oc->nama_kelas }}</span>
                        </label>
                    @empty
                        <div style="font-size: 0.84rem; color: #64748b;">Tidak ada kelas lain yang diajar.</div>
                    @endforelse
                </div>
            </div>

            <div style="margin-top: 10px; display: flex; justify-content: flex-end; gap: 12px;">
                <button type="button" onclick="closeSalinModal()" class="btn btn-outline" style="height: 42px; padding: 0 18px; border-radius: 8px; border: 1px solid #cbd5e1; background: #fff; cursor: pointer; font-weight: 600; color: #475569;">Batal</button>
                <button type="submit" class="btn btn-primary" style="height: 42px; padding: 0 24px; border-radius: 8px; border: none; background: #2563eb; color: #fff; cursor: pointer; font-weight: 600;" {{ $otherClasses->isEmpty() ? 'disabled' : '' }}>Salin Sekarang</button>
            </div>
        </form>
    </div>
</div>

<!-- PREVIEW MODAL -->
<div class="modal-overlay" id="previewModal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); z-index: 9999; align-items: center; justify-content: center; padding: 24px;">
    <div class="modal-content" style="background: #fff; border-radius: 12px; width: 90vw; height: 90vh; display: flex; flex-direction: column; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); border: 1px solid #cbd5e1; overflow: hidden; animation: modalIn 0.2s ease-out;">
        <div style="background: #f8fafc; padding: 18px 24px; border-bottom: 1px solid #cbd5e1; display: flex; justify-content: space-between; align-items: center;">
            <h3 id="preview_title" style="margin: 0; font-size: 1.2rem; font-weight: 700; color: #1e293b;">Preview Materi</h3>
            <div style="display: flex; align-items: center; gap: 12px;">
                <button onclick="toggleFullscreen()" style="border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px 12px; background: #fff; font-size: 0.84rem; cursor: pointer; color: #475569; font-weight: 600;"><i class="fa-solid fa-expand"></i> Fullscreen</button>
                <button onclick="closePreviewModal()" style="border: none; background: transparent; font-size: 1.25rem; cursor: pointer; color: #64748b;"><i class="fa-solid fa-xmark"></i></button>
            </div>
        </div>
        
        <div id="preview_container" style="flex: 1; background: #64748b; display: flex; align-items: center; justify-content: center; overflow: auto; position: relative;">
            <iframe id="preview_iframe" src="" style="width: 100%; height: 100%; border: none; display: none;"></iframe>
            <div id="preview_image_container" style="display: none; flex-direction: column; align-items: center; justify-content: center; gap: 16px; padding: 20px;">
                <img id="preview_img" src="" style="max-width: 100%; max-height: 70vh; object-fit: contain; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.3); transform: scale(1); transition: transform 0.2s ease;">
                <div style="display: flex; gap: 10px; background: rgba(0,0,0,0.6); padding: 8px 16px; border-radius: 20px; z-index: 10;">
                    <button onclick="zoomImg(0.1)" style="border: none; background: transparent; color: #fff; font-size: 1.1rem; cursor: pointer; padding: 0 8px;"><i class="fa-solid fa-magnifying-glass-plus"></i></button>
                    <button onclick="zoomImg(-0.1)" style="border: none; background: transparent; color: #fff; font-size: 1.1rem; cursor: pointer; padding: 0 8px;"><i class="fa-solid fa-magnifying-glass-minus"></i></button>
                    <button onclick="resetZoom()" style="border: none; background: transparent; color: #fff; font-size: 0.85rem; cursor: pointer; padding: 0 8px; font-weight: 600;">100%</button>
                </div>
            </div>
            <div id="preview_unsupported" style="display: none; text-align: center; color: #fff; padding: 40px;">
                <i class="fa-solid fa-file-powerpoint" style="font-size: 4rem; margin-bottom: 16px;"></i>
                <h4>File PowerPoint tidak dapat ditampilkan secara instan.</h4>
                <p style="margin-top: 8px;">Silakan unduh file untuk melihat presentasi secara lengkap.</p>
            </div>
        </div>
    </div>
</div>

<style>
    @keyframes modalIn {
        from { transform: scale(0.95); opacity: 0; }
        to { transform: scale(1); opacity: 1; }
    }
</style>

@endsection

@push('scripts')
<script>
    function handleFormSubmit(form) {
        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Menyimpan...';
        }
        return true;
    }

    function openUploadModal() {
        document.getElementById('uploadModal').style.display = 'flex';
    }
    
    function closeUploadModal() {
        document.getElementById('uploadModal').style.display = 'none';
    }

    function openEditModal(id) {
        // Fetch data via JSON endpoint
        fetch(`/guru/materi/${id}`)
            .then(res => {
                if (!res.ok) throw new Error();
                return res.json();
            })
            .then(data => {
                document.getElementById('editForm').action = `/guru/materi/${id}`;
                document.getElementById('edit_judul').value = data.judul;
                document.getElementById('edit_mapel').value = data.mata_pelajaran_id;
                document.getElementById('edit_status').value = data.status;
                document.getElementById('edit_deskripsi').value = data.deskripsi || '';
                document.getElementById('current_file_lbl').innerText = `File aktif: ${data.nama_file}`;

                // Check if this material is shared (i.e. other records exist for same path_file)
                fetch(`/guru/materi/${id}/edit`)
                    .then(r => r.json())
                    .then(editData => {
                        // Check if other classes share the same file
                        // If shared, we show the type selector
                        // We check this by querying path_file records count in server or client.
                        // Let's assume we can fetch the share count or pass it.
                        // Actually, we can fetch all materials of the teacher with the same path_file
                        // Let's make a quick request to the server, or we can just fetch it!
                        // Let's verify by requesting sharing check in JS!
                        // How about we just show the selector if the materi title doesn't contain class name,
                        // or always show it for flexibility! Always showing it is extremely safe and gives the user absolute control.
                        // Wait! The prompt says "Sediakan dua pilihan: Edit Materi Global atau Duplikat Khusus Kelas Ini."
                        // We can always display it! It's super clear.
                        // Let's show it!
                        document.getElementById('edit_type_wrapper').style.display = 'block';
                        document.getElementById('fallback_edit_type').disabled = true; // disable fallback
                    })
                    .catch(() => {
                        document.getElementById('edit_type_wrapper').style.display = 'none';
                        document.getElementById('fallback_edit_type').disabled = false;
                    });

                document.getElementById('editModal').style.display = 'flex';
            })
            .catch(() => alert('Gagal memuat data materi.'));
    }

    function closeEditModal() {
        document.getElementById('editModal').style.display = 'none';
    }

    function openSalinModal(id, judul) {
        document.getElementById('salinForm').action = `/guru/kelas/salin-materi/${id}`;
        document.getElementById('salin_materi_judul').innerText = judul;
        document.getElementById('salinModal').style.display = 'flex';
    }

    function closeSalinModal() {
        document.getElementById('salinModal').style.display = 'none';
    }

    // Preview Viewer
    let currentZoom = 1;
    function previewFile(id, judul, tipe, url) {
        document.getElementById('preview_title').innerText = `Preview: ${judul}`;
        
        const iframe = document.getElementById('preview_iframe');
        const imgContainer = document.getElementById('preview_image_container');
        const img = document.getElementById('preview_img');
        const unsupported = document.getElementById('preview_unsupported');
        
        iframe.style.display = 'none';
        imgContainer.style.display = 'none';
        unsupported.style.display = 'none';
        iframe.src = '';
        img.src = '';
        currentZoom = 1;
        img.style.transform = 'scale(1)';
        
        // Verify path file exists first
        fetch(url, { method: 'HEAD' })
            .then(res => {
                if (tipe === 'pdf') {
                    iframe.src = url;
                    iframe.style.display = 'block';
                } else if (tipe === 'image') {
                    img.src = url;
                    imgContainer.style.display = 'flex';
                } else {
                    unsupported.style.display = 'block';
                }
                document.getElementById('previewModal').style.display = 'flex';
            })
            .catch(() => {
                alert('File materi tidak ditemukan di storage server. Silakan upload ulang.');
            });
    }

    function closePreviewModal() {
        document.getElementById('previewModal').style.display = 'none';
        document.getElementById('preview_iframe').src = '';
    }

    function toggleFullscreen() {
        const el = document.getElementById('preview_container');
        if (!document.fullscreenElement) {
            el.requestFullscreen().catch(err => alert(`Gagal masuk fullscreen: ${err.message}`));
        } else {
            document.exitFullscreen();
        }
    }

    // Image Zoom controls
    function zoomImg(val) {
        const img = document.getElementById('preview_img');
        currentZoom += val;
        if (currentZoom < 0.2) currentZoom = 0.2;
        if (currentZoom > 3) currentZoom = 3;
        img.style.transform = `scale(${currentZoom})`;
    }

    function resetZoom() {
        const img = document.getElementById('preview_img');
        currentZoom = 1;
        img.style.transform = 'scale(1)';
    }
</script>
@endpush
