@extends('layouts.app')

@section('content')

<style>
    /* --- HANYA CSS SPESIFIK HALAMAN INI (Promes) --- */
    /* Warna elemen standar sudah diatur secara terpusat di app.blade.php */

    .accordion-promes .accordion-item {
        border: 1px solid var(--border-color);
        border-radius: 16px !important;
        margin-bottom: 20px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        overflow: hidden;
        background-color: transparent;
    }
    .accordion-promes .accordion-button {
        font-size: 1.05rem;
        padding: 1.25rem 1.5rem;
    }
    .accordion-promes .accordion-body {
        padding: 0;
    }
    
    /* Helper Kustom Tambahan */
    .bg-inner-card {
        background-color: var(--hover-bg);
    }
    .btn-pill { 
        border-radius: 50rem !important; 
    }
    .promes-item {
        background-color: var(--hover-bg);
        border: 1px solid var(--border-color);
    }
</style>

<div class="container py-4">
    {{-- HEADER --}}
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold"><i class="bi bi-calendar-range me-2 text-primary"></i>Program Semester (Promes)</h2>
            <p class="text-muted mb-0">Kelola distribusi alokasi waktu dan materi pokok per semester.</p>
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-secondary btn-pill px-4 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalCetakPromes">
                <i class="bi bi-printer me-1"></i> Cetak PDF
            </button>
            <button class="btn btn-primary btn-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalTambah">
                <i class="bi bi-plus-circle me-1"></i> Tambah Data
            </button>
        </div>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show shadow-sm border-0 border-start border-success border-4 bg-success bg-opacity-10 text-success rounded-4">
            <i class="bi bi-check-circle-fill me-2"></i> {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    {{-- GRUPING DATA --}}
    @php
        $groupedPromes = $promes->groupBy(function($item) {
            return $item->subject->name ?? 'Tanpa Mata Pelajaran';
        })->map(function($group) {
            return $group->sortBy(function($item) {
                return strtolower($item->semester) == 'ganjil' ? 1 : 2;
            })->values(); 
        });
    @endphp

    {{-- ACCORDION TABEL DATA --}}
    <div class="accordion accordion-promes" id="accordionPromesMapel">
        @forelse($groupedPromes as $subjectName => $subjectPromes)
            <div class="accordion-item shadow-sm">
                <h2 class="accordion-header" id="heading-{{ $loop->index }}">
                    <button class="accordion-button fw-bold collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ $loop->index }}" aria-expanded="false" aria-controls="collapse-{{ $loop->index }}">
                        <div class="d-flex align-items-center w-100">
                            <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="bi bi-calendar-range-fill"></i>
                            </div>
                            <span class="fs-5">{{ $subjectName }}</span>
                            <span class="badge bg-primary ms-auto me-3 rounded-pill px-3 py-2">{{ $subjectPromes->count() }} Data Promes</span>
                        </div>
                    </button>
                </h2>
                <div id="collapse-{{ $loop->index }}" class="accordion-collapse collapse" aria-labelledby="heading-{{ $loop->index }}">
                    <div class="accordion-body">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle text-center mb-0" style="font-size: 0.9rem;">
                                <thead class="table-light">
                                    <tr>
                                        <th rowspan="2" class="align-middle px-3">Sem</th>
                                        <th rowspan="2" class="align-middle text-start" width="25%">Materi Pokok</th>
                                        <th rowspan="2" class="align-middle">JP</th>
                                        <th colspan="6">Distribusi Waktu (Checklist)</th>
                                        <th rowspan="2" class="align-middle" width="120">Aksi</th>
                                    </tr>
                                    <tr>
                                        <th>Jul / Jan</th>
                                        <th>Agt / Feb</th>
                                        <th>Sep / Mar</th>
                                        <th>Okt / Apr</th>
                                        <th>Nov / Mei</th>
                                        <th>Des / Jun</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($subjectPromes as $item)
                                    <tr>
                                        <td class="px-3">
                                            @if(strtolower($item->semester) == 'ganjil')
                                                <span class="badge bg-primary bg-opacity-10 text-primary border border-primary-subtle rounded-pill d-block mb-1 px-3 py-2">Ganjil</span>
                                            @else
                                                <span class="badge bg-success bg-opacity-10 text-success border border-success-subtle rounded-pill d-block mb-1 px-3 py-2">Genap</span>
                                            @endif
                                            <small class="text-muted fw-bold" style="font-size: 0.75rem;">{{ $item->academic_year }}</small>
                                        </td>
                                        
                                        <td class="text-start">
                                            <div style="max-height: 80px; overflow-y: auto; line-height: 1.6;">
                                                {{ $item->topic }}
                                            </div>
                                        </td>

                                        <td><span class="badge bg-info bg-opacity-10 text-info border border-info-subtle rounded-pill px-3 py-2">{{ $item->allocation_hours }} JP</span></td>
                                        
                                        @php 
                                            $monthPairs = [
                                                ['Juli', 'Januari'], ['Agustus', 'Februari'], ['September', 'Maret'],
                                                ['Oktober', 'April'], ['November', 'Mei'], ['Desember', 'Juni'],
                                            ];
                                        @endphp

                                        @foreach($monthPairs as $pair)
                                            <td>
                                                @if(isset($item->monthly_distribution[$pair[0]]) || isset($item->monthly_distribution[$pair[1]]))
                                                    <span class="text-success fw-bold fs-5"><i class="bi bi-check-circle-fill"></i></span>
                                                @else
                                                    <span class="text-muted" style="opacity: 0.25;">-</span>
                                                @endif
                                            </td>
                                        @endforeach

                                        <td>
                                            <div class="d-flex justify-content-center gap-2">
                                                <button class="btn btn-sm btn-outline-warning rounded-circle" style="width:35px; height:35px;" title="Edit Data" data-bs-toggle="modal" data-bs-target="#modalEdit{{ $item->id }}">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <a href="{{ route('promes.printSingle', $item->id) }}" target="_blank" class="btn btn-sm btn-outline-success rounded-circle" style="width:35px; height:35px;" title="Cetak Promes ini">
                                                    <i class="bi bi-printer-fill"></i>
                                                </a>
                                                <form action="{{ route('promes.destroy', $item->id) }}" method="POST" onsubmit="return confirm('Hapus data ini?')">
                                                    @csrf @method('DELETE')
                                                    <button class="btn btn-sm btn-outline-danger rounded-circle" style="width:35px; height:35px;" title="Hapus Data"><i class="bi bi-trash"></i></button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        @empty
            <div class="card modern-card border-0 py-5 text-center">
                <div class="card-body">
                    <div class="mb-3 text-muted opacity-50"><i class="bi bi-calendar-x" style="font-size: 4rem;"></i></div>
                    <h5 class="fw-bold">Belum ada data Program Semester.</h5>
                    <p class="text-muted">Klik tombol "Tambah Data" untuk menyusun distribusi waktu.</p>
                </div>
            </div>
        @endforelse
    </div>
</div>

{{-- MODAL EDIT (LOOPING) --}}
@foreach($promes as $item)
<div class="modal fade text-start" id="modalEdit{{ $item->id }}" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content shadow-lg border-0 rounded-4">
            <div class="modal-header bg-warning border-0 rounded-top-4 py-3 text-dark">
                <h5 class="modal-title fw-bold"><i class="bi bi-pencil-square me-2"></i> Edit Program Semester</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('promes.update', $item->id) }}" method="POST">
                @csrf @method('PUT')
                <div class="modal-body p-4">
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-muted text-uppercase">Mata Pelajaran</label>
                            <select name="subject_id" id="subject_id" class="form-select rounded-pill py-2" required>
                                <option value="">Pilih Mapel...</option>
                                @foreach($subjects as $subject)
                                    <option value="{{ $subject->id }}" {{ $item->subject_id == $subject->id ? 'selected' : '' }}>{{ $subject->name }} ({{ $subject->code }})</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label fw-bold small text-muted text-uppercase">Tahun Ajaran</label>
                            <input type="text" name="academic_year" class="form-control rounded-pill py-2" value="{{ $item->academic_year }}" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">Semester</label>
                            <input type="hidden" name="semester" value="{{ $item->semester }}">
                            <input type="text" class="form-control rounded-pill py-2" value="{{ $item->semester }}" readonly>
                            <small class="text-muted" style="font-size: 10px">*Semester tidak bisa diubah saat edit</small>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">Alokasi JP</label>
                            <input type="number" name="allocation_hours" class="form-control rounded-pill py-2" value="{{ $item->allocation_hours }}" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase">Materi Pokok</label>
                        <textarea name="topic" class="form-control rounded-4" rows="2" required>{{ $item->topic }}</textarea>
                    </div>

                    <label class="fw-bold mb-2 mt-2 text-primary">Edit Distribusi Waktu (Semester {{ $item->semester }})</label>
                    <div class="table-responsive border rounded-4 overflow-hidden">
                        <table class="table table-bordered table-sm text-center mb-0">
                            <thead class="table-secondary">
                                <tr>
                                    <th class="py-2">Bulan</th><th>Mgg 1</th><th>Mgg 2</th><th>Mgg 3</th><th>Mgg 4</th><th>Mgg 5</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    if ($item->semester == 'Ganjil') {
                                        $editMonths = ['Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
                                    } else {
                                        $editMonths = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni'];
                                    }
                                @endphp
                                
                                @foreach($editMonths as $month)
                                <tr>
                                    <td class="fw-bold text-start ps-4 align-middle">{{ $month }}</td>
                                    @for($w=1; $w<=5; $w++)
                                        @php
                                            $checked = '';
                                            if(isset($item->monthly_distribution[$month]) && in_array((string)$w, $item->monthly_distribution[$month])) {
                                                $checked = 'checked';
                                            }
                                        @endphp
                                        <td class="align-middle">
                                            <input type="checkbox" name="monthly_distribution[{{ $month }}][]" value="{{ $w }}" class="form-check-input mt-1" style="cursor:pointer; width: 1.2rem; height: 1.2rem;" {{ $checked }}>
                                        </td>
                                    @endfor
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer border-0 py-3 bg-inner-card rounded-bottom-4">
                    <button type="button" class="btn btn-outline-secondary btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning btn-pill px-5 fw-bold text-dark"><i class="bi bi-check-circle me-1"></i> Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endforeach

{{-- MODAL TAMBAH BARU --}}
<div class="modal fade" id="modalTambah" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content shadow-lg border-0 rounded-4">
            <div class="modal-header bg-primary border-0 text-white rounded-top-4 py-3">
                <h5 class="modal-title fw-bold"><i class="bi bi-plus-circle me-2"></i> Tambah Program Semester</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('promes.store') }}" method="POST">
                @csrf
                <div class="modal-body p-4">
                    {{-- HEADER DATA GLOBAL --}}
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-muted text-uppercase">Mata Pelajaran</label>
                            <select name="subject_id" id="subject_id" class="form-select rounded-pill py-2" required>
                                <option value="">Pilih Mapel...</option>
                                @foreach($subjects as $subject)
                                    <option value="{{ $subject->id }}">{{ $subject->name }} ({{ $subject->code }})</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-muted text-uppercase">Tahun Ajaran</label>
                            <input type="text" name="academic_year" class="form-control rounded-pill py-2" placeholder="Cth: 2024/2025" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-muted text-uppercase">Semester</label>
                            <select name="semester" id="selectSemester" class="form-select rounded-pill py-2" required onchange="resetPromesContainer()">
                                <option value="Ganjil">Ganjil (Juli - Des)</option>
                                <option value="Genap">Genap (Jan - Juni)</option>
                            </select>
                        </div>
                    </div>

                    {{-- FITUR AI: TARIK PROTA & DISTRIBUSI OTOMATIS --}}
                    <div class="p-4 mb-4 rounded-4 border border-primary border-opacity-50" style="background: linear-gradient(145deg, rgba(59,130,246,0.1) 0%, rgba(59,130,246,0.02) 100%);">
                        <label class="form-label fw-bold text-primary fs-5 mb-3">
                            <i class="bi bi-robot me-2"></i> Tarik Data Prota & Distribusi Cerdas AI
                        </label>
                        <div class="row align-items-center">
                            <div class="col-md-8 mb-2">
                                <select id="ai_grade_level" class="form-select rounded-pill py-2">
                                    <option value="">-- Pilih Kelas Target Prota --</option>
                                    <option value="X">Kelas X</option>
                                    <option value="XI">Kelas XI</option>
                                    <option value="XII">Kelas XII</option>
                                </select>
                                <small class="text-primary opacity-75 mt-2 d-block">AI akan mengambil seluruh materi Prota sesuai kelas dan mendistribusikan jadwalnya.</small>
                            </div>
                            <div class="col-md-4 mb-2">
                                <button type="button" id="btnGenerateAI" class="btn btn-primary btn-pill w-100 fw-bold shadow-sm py-2">
                                    <i class="bi bi-magic me-1"></i> Auto-Distribusi
                                </button>
                            </div>
                        </div>
                    </div>

                    {{-- CONTAINER DINAMIS UNTUK MATERI & CHECKLIST MINGGUAN --}}
                    <div id="promesContainer">
                        </div>

                    <button type="button" class="btn btn-outline-secondary btn-sm btn-pill px-4 mt-3" onclick="addManualRow()">
                        <i class="bi bi-plus-circle me-1"></i> Tambah Materi Manual
                    </button>
                </div>
                <div class="modal-footer border-0 py-3 bg-inner-card rounded-bottom-4">
                    <button type="button" class="btn btn-outline-secondary btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-pill px-5 fw-bold shadow-sm"><i class="bi bi-save me-1"></i> Simpan Data Promes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function changeMonths() {
        const semester = document.getElementById('selectSemester').value;
        const container = document.getElementById('monthContainer');
        if(!container) return; 
        let months = (semester === 'Ganjil') 
            ? ['Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember']
            : ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni'];

        let html = '';
        months.forEach(month => {
            html += `<tr><td class="fw-bold text-start ps-3 align-middle">${month}</td>` +
                    `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${month}][]" value="1"></td>` +
                    `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${month}][]" value="2"></td>` +
                    `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${month}][]" value="3"></td>` +
                    `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${month}][]" value="4"></td>` +
                    `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${month}][]" value="5"></td></tr>`;
        });
        container.innerHTML = html;
    }
    
    document.addEventListener("DOMContentLoaded", function() { changeMonths(); });
</script>

{{-- MODAL FILTER CETAK PROMES --}}
<div class="modal fade" id="modalCetakPromes" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-secondary border-0 text-white rounded-top-4 py-3">
                <h5 class="modal-title fw-bold"><i class="bi bi-printer-fill me-2"></i> Konfigurasi Cetak Promes</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('promes.print') }}" method="GET" target="_blank">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold small text-muted text-uppercase">Pilih Mata Pelajaran</label>
                        <select name="subject_id" class="form-select rounded-pill py-2" required>
                            <option value="">-- Pilih Mapel --</option>
                            @foreach($subjects as $subject)
                                <option value="{{ $subject->id }}">{{ $subject->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold small text-muted text-uppercase">Pilih Semester</label>
                        <select name="semester" class="form-select rounded-pill py-2" required>
                            <option value="Ganjil">Semester Ganjil</option>
                            <option value="Genap">Semester Genap</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold small text-muted text-uppercase">Tahun Ajaran</label>
                        <input type="text" name="tahun_ajaran" class="form-control rounded-pill py-2" placeholder="Contoh: 2024/2025">
                    </div>
                </div>
                <div class="modal-footer border-0 py-3 bg-inner-card rounded-bottom-4">
                    <button type="button" class="btn btn-outline-secondary btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-pill px-5 fw-bold shadow-sm">
                        <i class="bi bi-printer me-1"></i> Mulai Cetak
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    let rowCount = 0; 

    // Fungsi Render HTML Checklist Per Materi (Diupdate untuk Dark/Light Mode adaptif)
    function generatePromesItemHTML(index, topic = '', jp = '', distribution = null, semester = 'Ganjil') {
        const months = (semester === 'Ganjil') 
            ? ['Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember']
            : ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni'];

        let tableRows = '';
        months.forEach(month => {
            let tds = `<td class="fw-bold text-start ps-3 align-middle">${month}</td>`;
            for(let w=1; w<=5; w++) {
                let isChecked = '';
                if(distribution && distribution[month] && distribution[month].includes(w)) {
                    isChecked = 'checked';
                }
                tds += `<td class="align-middle"><input type="checkbox" class="form-check-input mt-1" style="cursor:pointer; width:1.2rem; height:1.2rem;" name="monthly_distribution[${index}][${month}][]" value="${w}" ${isChecked}></td>`;
            }
            tableRows += `<tr>${tds}</tr>`;
        });

        // Menggunakan bg-inner-card agar beradaptasi dengan warna tema otomatis
        return `
            <div class="promes-item rounded-4 p-4 mb-4 position-relative shadow-sm bg-inner-card">
                <button type="button" class="btn btn-sm btn-danger rounded-circle position-absolute top-0 end-0 m-3 btn-remove-promes" style="width:35px; height:35px;" onclick="this.closest('.promes-item').remove()">
                    <i class="bi bi-trash"></i>
                </button>
                <div class="row mb-3 pe-5">
                    <div class="col-md-9">
                        <label class="form-label fw-bold small text-muted text-uppercase mb-2">Materi Pokok / Kompetensi Dasar</label>
                        <textarea name="topic[]" class="form-control rounded-4" rows="2" required placeholder="Tuliskan materi pokok...">${topic}</textarea>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold small text-muted text-uppercase mb-2">Alokasi Waktu</label>
                        <div class="input-group">
                            <input type="number" name="allocation_hours[]" class="form-control border-end-0" value="${jp}" required placeholder="JP">
                            <span class="input-group-text bg-transparent border-start-0">JP</span>
                        </div>
                    </div>
                </div>
                <div class="table-responsive mt-3 border rounded-4 overflow-hidden">
                    <table class="table table-bordered table-sm text-center mb-0">
                        <thead class="table-secondary">
                            <tr><th class="py-2">Bulan</th><th>Mgg 1</th><th>Mgg 2</th><th>Mgg 3</th><th>Mgg 4</th><th>Mgg 5</th></tr>
                        </thead>
                        <tbody>${tableRows}</tbody>
                    </table>
                </div>
            </div>
        `;
    }

    function resetPromesContainer() {
        document.getElementById('promesContainer').innerHTML = '';
        rowCount = 0;
        addManualRow();
    }

    function addManualRow() {
        const semester = document.getElementById('selectSemester').value;
        const container = document.getElementById('promesContainer');
        container.innerHTML += generatePromesItemHTML(rowCount, '', '', null, semester);
        rowCount++;
    }

    document.addEventListener("DOMContentLoaded", function() {
        resetPromesContainer();
        
        const btnGenerateAI = document.getElementById('btnGenerateAI');
        btnGenerateAI.addEventListener('click', async function() {
            const subjectId = document.getElementById('subject_id').value;
            const semester = document.getElementById('selectSemester').value;
            const gradeLevel = document.getElementById('ai_grade_level').value;

            if(!subjectId || !gradeLevel) {
                alert("Pilih Mata Pelajaran dan Kelas Target Prota terlebih dahulu!");
                return;
            }

            const originalText = btnGenerateAI.innerHTML;
            btnGenerateAI.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Menarik Data...';
            btnGenerateAI.disabled = true;

            try {
                const protaRes = await fetch('{{ route("api.promes.get-prota") }}', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}'},
                    body: JSON.stringify({ subject_id: subjectId, grade_level: gradeLevel, semester: semester })
                });
                const protaData = await protaRes.json();

                if(protaData.data.length === 0) {
                    alert(`Tidak ada data Prota untuk Kelas ${gradeLevel} di Semester ${semester}. Silakan isi Prota terlebih dahulu!`);
                    btnGenerateAI.innerHTML = originalText;
                    btnGenerateAI.disabled = false;
                    return;
                }

                const materiList = protaData.data.map(item => ({
                    materi_pokok: item.content_description,
                    alokasi_jp: parseInt(item.time_allocation)
                }));

                btnGenerateAI.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> AI Mendistribusikan...';
                
                const aiRes = await fetch('{{ route("api.ai.generate-promes") }}', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}'},
                    body: JSON.stringify({ semester: semester, materi_list: materiList })
                });
                const aiData = await aiRes.json();

                if(aiData.status === 'success') {
                    const container = document.getElementById('promesContainer');
                    container.innerHTML = ''; 
                    rowCount = 0;
                    
                    aiData.results.forEach((item) => {
                        container.innerHTML += generatePromesItemHTML(rowCount, item.materi_pokok, item.alokasi_jp, item.jadwal, semester);
                        rowCount++;
                    });
                } else {
                    alert('Gagal Generate: ' + aiData.message);
                }

            } catch(e) {
                alert('Terjadi kesalahan sistem.');
                console.error(e);
            } finally {
                btnGenerateAI.innerHTML = originalText;
                btnGenerateAI.disabled = false;
            }
        });
    });
</script>
@endsection