@extends('admin.layout')

@section('title', '')

@section('content')
    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="bi bi-book me-1"></i> Daftar Mata Pelajaran pada setiap Fase</h5>
            <p class="mb-0 small text-white-50">Halaman manajemen mata pelajaran di tiap fase dan tingkat</p>
        </div>
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <p class="mb-0">Daftar Mata Pelajaran per Fase</p>
                    @php $activePeriode = \App\Services\PeriodeService::getActive(); @endphp
                    @if($activePeriode)
                        <small class="text-muted">Tahun Pelajaran: {{ $activePeriode->tahun_pelajaran }} &middot; Semester: {{ $activePeriode->semester }}</small>
                    @else
                        <small class="text-muted">Belum ada periode aktif</small>
                    @endif
                    @php
                        $tingkatForFase = function($fase){
                            $f = strtoupper((string)$fase);
                            if($f === 'A') return '1 & 2';
                            if($f === 'B') return '3 & 4';
                            if($f === 'C') return '5 & 6';
                            return '-';
                        };
                    @endphp
                </div>
                <div>
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalTambahMapel">
                        <i class="bi bi-plus-lg"></i> Tambah Mata Pelajaran
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <style>
                    /* truncate long text in table cells to match input widths */
                    .mp-table td { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
                </style>
                <table class="table table-bordered table-hover align-middle mp-table" style="table-layout: fixed;">
                    <thead class="table-light">
                        <tr>
                            <th style="width:60px;">Fase</th>
                            <th style="width:80px;">Tingkat</th>
                            <th style="width:100px;">Kelas</th>
                            <th style="width:90px;">Urutan</th>
                            <th style="width:300px;">Mata Pelajaran</th>
                            <th style="width:140px;">Materi 1</th>
                            <th style="width:140px;">Materi 2</th>
                            <th style="width:140px;">Materi 3</th>
                            <th style="width:140px;">Materi 4</th>
                            <th style="width:140px;">Materi 5</th>
                            <th style="width:140px;">Materi 6</th>
                            <th style="width:120px;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($mataPelajarans ?? [] as $mp)
                            <tr>
                                <td>{{ $mp->fase ?? ($mp['fase'] ?? '-') }}</td>
                                <td>{{ $tingkatForFase($mp->fase ?? ($mp['fase'] ?? '-')) }}</td>
                                <td>
                                    @if(is_array($mp->kelas ?? ($mp['kelas'] ?? null)) || (isset($mp->kelas) && $mp->kelas instanceof \Illuminate\Support\Collection))
                                        @php
                                            $list = collect($mp->kelas ?? ($mp['kelas'] ?? []))->map(function($k){ return $k->nama ?? ($k['nama'] ?? (string)$k); })->implode(', ');
                                        @endphp
                                        {{ $list }}
                                    @else
                                        {{ $mp->kelas->nama ?? ($mp->kelas ?? ($mp['kelas'] ?? '-')) }}
                                    @endif
                                </td>
                                <td style="text-align:center">{{ $mp->urutan ?? ($mp['urutan'] ?? '-') }}</td>
                                <td>{{ $mp->nama ?? ($mp['mata_pelajaran'] ?? ($mp['nama_mapel'] ?? '-')) }}</td>
                                <td>{{ $mp->materi1 ?? ($mp['materi1'] ?? '-') }}</td>
                                <td>{{ $mp->materi2 ?? ($mp['materi2'] ?? '-') }}</td>
                                <td>{{ $mp->materi3 ?? ($mp['materi3'] ?? '-') }}</td>
                                <td>{{ $mp->materi4 ?? ($mp['materi4'] ?? '-') }}</td>
                                <td>{{ $mp->materi5 ?? ($mp['materi5'] ?? '-') }}</td>
                                <td>{{ $mp->materi6 ?? ($mp['materi6'] ?? '-') }}</td>
                                <td class="text-center">
                                    <a href="{{ route('admin.mata-pelajaran.edit', $mp->id ?? ($mp['id'] ?? '')) }}" class="btn btn-sm btn-primary me-1" title="Edit">
                                        <i class="bi bi-pencil" aria-hidden="true"></i>
                                    </a>
                                    <form action="{{ route('admin.mata-pelajaran.destroy', $mp->id ?? ($mp['id'] ?? '')) }}" method="POST" style="display:inline-block;" onsubmit="return confirm('Yakin ingin menghapus mata pelajaran ini?');">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-sm btn-danger" title="Hapus">
                                            <i class="bi bi-trash" aria-hidden="true"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="12" class="text-center">Tidak ada data mata pelajaran.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

                <!-- Modal: Tambah Mata Pelajaran -->
                @php
                    $kelasList = $kelas ?? \App\Models\Kelas::all();
                    // if current user is a guru, limit kelasList to kelas they own
                    try {
                        if(auth()->check() && optional(auth()->user())->role === 'guru'){
                            $guruId = auth()->id();
                            $kelasList = collect($kelasList)->filter(function($x) use($guruId){
                                return (isset($x->walikelas_id) && $x->walikelas_id == $guruId) || (isset($x['walikelas_id']) && $x['walikelas_id'] == $guruId);
                            })->values();
                        }
                    } catch (\Throwable $e) {}

                    $phases = collect($kelasList)->map(function($k){ return $k->fase ?? ($k['fase'] ?? null); })->filter()->unique()->values();

                    // defaults for guru (if any)
                    $defaultFase = null; $defaultTingkat = null; $defaultKelasId = null;
                    try {
                        if(auth()->check() && optional(auth()->user())->role === 'guru'){
                            $first = collect($kelasList)->first();
                            if($first){
                                $defaultFase = $first->fase ?? ($first['fase'] ?? null);
                                $defaultTingkat = $first->tingkat ?? ($first['tingkat'] ?? null);
                                $defaultKelasId = $first->id ?? ($first['id'] ?? null);
                            }
                        }
                    } catch (\Throwable $e) {}
                @endphp

                <div class="modal fade" id="modalTambahMapel" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <form method="POST" action="{{ route('admin.mata-pelajaran.store') }}">
                                @csrf
                                <div class="modal-header bg-success bg-opacity-25">
                                    <h5 class="modal-title text-dark">Tambah Mata Pelajaran</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="row g-2">
                                        <div class="col-md-4">
                                            <label class="form-label">Fase</label>
                                            <select id="mp-fase" name="fase" class="form-select" required>
                                                <option value="">Pilih Fase</option>
                                                @foreach($phases as $ph)
                                                    <option value="{{ $ph }}">{{ $ph }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Tingkat</label>
                                            <select id="mp-tingkat" name="tingkat" class="form-select" required>
                                                <option value="">Pilih Tingkat</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Kelas</label>
                                            <select id="mp-kelas" name="kelas_id" class="form-select">
                                                <option value="">Pilih Kelas (opsional)</option>
                                                @foreach($kelasList as $k)
                                                    <option data-tingkat="{{ $k->tingkat ?? ($k['tingkat'] ?? '') }}" value="{{ $k->id ?? ($k['id'] ?? ($k['nama'] ?? $k)) }}">{{ $k->nama ?? ($k['nama'] ?? $k) }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div class="col-md-9">
                                            <label class="form-label">Mata Pelajaran</label>
                                            <input name="nama" class="form-control" placeholder="Nama mata pelajaran" required />
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Urutan</label>
                                            <input name="urutan" type="number" class="form-control" placeholder="Urutan" min="1" />
                                        </div>

                                        <div class="col-12">
                                            <label class="form-label">Materi</label>
                                            @php
                                                $tabColors = ['#0d6efd', '#198754', '#ffc107', '#dc3545', '#6f42c1', '#0dcaf0'];
                                            @endphp
                                            <ul class="nav nav-tabs" id="materiTabs" role="tablist">
                                                @for($i=1;$i<=6;$i++)
                                                    @php $color = $tabColors[$i-1] ?? '#6c757d'; @endphp
                                                    <li class="nav-item" role="presentation">
                                                        <button class="nav-link @if($i==1) active @endif" id="tab-materi-{{ $i }}" data-bs-toggle="tab" data-bs-target="#materi-{{ $i }}" type="button" role="tab" aria-controls="materi-{{ $i }}" aria-selected="{{ $i==1 ? 'true':'false' }}" style="background-color: {{ $color }}; color: #fff; border-color: {{ $color }};">
                                                            Materi {{ $i }}
                                                        </button>
                                                    </li>
                                                @endfor
                                            </ul>
                                            <div class="tab-content border p-2" id="materiTabsContent">
                                                @for($i=1;$i<=6;$i++)
                                                    <div class="tab-pane fade @if($i==1) show active @endif" id="materi-{{ $i }}" role="tabpanel" aria-labelledby="tab-materi-{{ $i }}">
                                                        <textarea name="materi{{ $i }}" class="form-control" rows="4" placeholder="Isikan Deskripsi Lingkup Materi Pembelajaran">{{ old('materi'.$i) }}</textarea>
                                                    </div>
                                                @endfor
                                            </div>
                                        </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">Simpan</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                @push('scripts')
                    <script>
                        (function(){
                            const faseSelect = document.getElementById('mp-fase');
                            const tingkatSelect = document.getElementById('mp-tingkat');
                            const kelasSelect = document.getElementById('mp-kelas');

                            const tingkatOptions = {
                                'A': ['1','2'],
                                'B': ['3','4'],
                                'C': ['5','6']
                            };

                            function populateTingkat(fase){
                                tingkatSelect.innerHTML = '<option value="">Pilih Tingkat</option>';
                                const list = tingkatOptions[fase] || [];
                                list.forEach(t=>{
                                    const opt = document.createElement('option');
                                    opt.value = t; opt.text = t;
                                    tingkatSelect.appendChild(opt);
                                });
                                filterKelasByTingkat();
                            }

                            function filterKelasByTingkat(){
                                const tingkat = tingkatSelect.value;
                                Array.from(kelasSelect.options).forEach(opt=>{
                                    if(!opt.value) return;
                                    const t = opt.getAttribute('data-tingkat') || '';
                                    opt.style.display = (!tingkat || t === tingkat) ? '' : 'none';
                                });
                            }

                            faseSelect && faseSelect.addEventListener('change', function(){ populateTingkat(this.value); });
                            tingkatSelect && tingkatSelect.addEventListener('change', filterKelasByTingkat);

                            // Auto-select for guru accounts
                            @if(auth()->check() && optional(auth()->user())->role === 'guru')
                                try {
                                    const defFase = {!! json_encode($defaultFase) !!};
                                    const defTingkat = {!! json_encode($defaultTingkat) !!};
                                    const defKelas = {!! json_encode($defaultKelasId) !!};
                                    if(defFase){
                                        faseSelect.value = defFase;
                                        populateTingkat(defFase);
                                        // small timeout to ensure options added
                                        setTimeout(function(){
                                            if(defTingkat){ tingkatSelect.value = defTingkat; }
                                            filterKelasByTingkat();
                                            if(defKelas){ kelasSelect.value = defKelas; }
                                        }, 10);
                                    }
                                } catch(e){}
                            @endif
                        })();
                    </script>
                @endpush
        </div>
    </div>
@endsection
