<?php $__env->startSection('content'); ?>

<style>
    /* --- 1. Dark Mode & Style Overrides --- */
    [data-theme="dark"] .card,
    [data-theme="dark"] .modal-content {
        background-color: var(--bg-card);
        border: 1px solid var(--border-color);
        color: var(--text-main);
    }
    [data-theme="dark"] .card-header,
    [data-theme="dark"] .modal-header,
    [data-theme="dark"] .modal-footer { border-color: var(--border-color); }
    [data-theme="dark"] .bg-light,
    [data-theme="dark"] .bg-white {
        background-color: var(--bg-card) !important;
        color: var(--text-main) !important;
        border-color: var(--border-color) !important;
    }
    [data-theme="dark"] .form-control,
    [data-theme="dark"] .form-select {
        background-color: var(--hover-bg);
        border-color: var(--border-color);
        color: var(--text-main);
    }
    [data-theme="dark"] .table { color: var(--text-main); border-color: var(--border-color); }
    [data-theme="dark"] .table-hover tbody tr:hover { background-color: rgba(255, 255, 255, 0.05); }
    [data-theme="dark"] .btn-close { filter: invert(1) grayscale(100%) brightness(200%); }

    /* --- 2. Animasi Tombol AI --- */
    .btn-ai-gradient {
        background: linear-gradient(45deg, #2c3e50, #4ca1af);
        color: white;
        border: none;
        transition: all 0.3s ease;
    }
    .btn-ai-gradient:hover {
        background: linear-gradient(45deg, #4ca1af, #2c3e50);
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        color: white;
    }

    /* --- 3. Tampilan Kertas (Paper View) untuk Modal Lihat --- */
    .paper-view {
        background-color: white;
        padding: 40px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        color: #333;
        font-family: 'Times New Roman', Times, serif;
        line-height: 1.6;
        font-size: 12pt;
        border-radius: 4px;
    }
    .paper-header {
        border-bottom: 3px double #333;
        padding-bottom: 15px;
        margin-bottom: 25px;
        text-align: center;
    }
    .paper-header h3 { margin: 0; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; }
    .paper-header h5 { margin: 5px 0 0; font-weight: normal; }

    /* Label Info di Kertas */
    .info-row { display: flex; margin-bottom: 6px; }
    .info-label { width: 180px; font-weight: bold; flex-shrink: 0; }
    .info-sep { width: 15px; flex-shrink: 0; text-align: center; }
    .info-val { flex-grow: 1; }

    /* Section Title di Kertas */
    .section-title {
        background-color: #f8f9fa;
        color: #000;
        padding: 8px 12px;
        font-weight: bold;
        text-transform: uppercase;
        margin-top: 25px;
        margin-bottom: 15px;
        border-left: 5px solid #0d6efd;
        border-bottom: 1px solid #ddd;
    }

    /* --- 4. Perbaikan Tabulasi & Indentasi (Hanging Indent) --- */
    .formatted-text { text-align: justify; white-space: pre-line; }
    .indent-block { margin-left: 20px; text-align: justify; }
    .sub-point-title { font-weight: bold; font-style: italic; margin-top: 10px; margin-left: 20px; }
    .sub-point-content { margin-left: 40px; text-align: justify; }

    /* --- 5. Custom Fullscreen Modal --- */
    .modal-fullscreen-custom { width: 100vw; max-width: none; height: 100%; margin: 0; }
    .modal-fullscreen-custom .modal-content { height: 100%; border: 0; border-radius: 0; }
    .modal-fullscreen-custom .modal-body { overflow-y: auto; background-color: #525659; padding: 30px; }
    .modal-fullscreen-custom .paper-view { max-width: 21cm; margin: 0 auto; min-height: 29.7cm; }

    /* --- 6. Styling untuk Accordion Grup Mapel --- */
    .accordion-modul .accordion-item {
        border: 1px solid var(--border-color, #dee2e6);
        border-radius: 8px !important;
        margin-bottom: 15px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        overflow: hidden;
    }
    .accordion-modul .accordion-button {
        font-size: 1.05rem;
        padding: 1rem 1.25rem;
    }
    .accordion-modul .accordion-button:not(.collapsed) {
        background-color: #f8f9fa;
        color: #0d6efd;
        box-shadow: inset 0 -1px 0 rgba(0,0,0,.125);
    }
    /* Dark Mode Accordion */
    [data-theme="dark"] .accordion-modul .accordion-item { background-color: var(--bg-card); border-color: var(--border-color); }
    [data-theme="dark"] .accordion-modul .accordion-button { background-color: var(--bg-card); color: var(--text-main); }
    [data-theme="dark"] .accordion-modul .accordion-button:not(.collapsed) { background-color: var(--hover-bg); color: #6ea8fe; border-bottom: 1px solid var(--border-color); }
    [data-theme="dark"] .accordion-modul .accordion-button::after { filter: invert(1); }
</style>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold" style="color: #1e293b;">Modul Ajar</h2>
            <p class="text-muted">Kelola dan cetak modul ajar Kurikulum Merdeka.</p>
        </div>
        <div>
            <button type="button" class="btn btn-secondary me-2 shadow-sm" onclick="openPrintModal()">
                <i class="bi bi-printer"></i> Cetak Terpilih
            </button>
            <button type="button" class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#modalModul">
                <i class="bi bi-plus-lg me-1"></i> Buat Modul Baru
            </button>
        </div>
    </div>

    <?php if(session('success')): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo e(session('success')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if(session('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo e(session('error')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

   
    <?php
        $groupedModules = $modules->groupBy(function($item) {
            $isPraktikum = (strpos(strtolower($item->model_learning ?? ''), 'praktikum') !== false || 
                            strpos(strtolower($item->model_learning ?? ''), 'kerja bengkel') !== false);
            
            $groupName = $item->subject->name ?? 'Tanpa Mata Pelajaran';
            
            if ($isPraktikum) {
                return $groupName . ' (Praktikum)';
            }
            return $groupName;
            
        })->map(function($group) {
            return $group->sortBy(function($item) {
                $gradeOrder = ['X' => 1, 'XI' => 2, 'XII' => 3];
                $grade = $gradeOrder[$item->grade_level] ?? 99;
                
                $sem = strtolower($item->semester) == 'ganjil' ? 1 : 2;
                
                return $grade . '-' . $sem;
            })->values(); 
        });
    ?>

    <div class="accordion accordion-modul" id="accordionModulMapel">
        <?php $__empty_1 = true; $__currentLoopData = $groupedModules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subjectName => $subjectModules): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <div class="accordion-item border-0 shadow-sm">
                <h2 class="accordion-header" id="heading-<?php echo e($loop->index); ?>">
                    
                    <button class="accordion-button fw-bold collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo e($loop->index); ?>" aria-expanded="false" aria-controls="collapse-<?php echo e($loop->index); ?>">
                        <i class="bi bi-journal-bookmark-fill me-2 text-primary"></i> 
                        <?php echo e($subjectName); ?>

                        <span class="badge bg-primary ms-3 rounded-pill"><?php echo e($subjectModules->count()); ?> Modul</span>
                    </button>
                </h2>
                
                <div id="collapse-<?php echo e($loop->index); ?>" class="accordion-collapse collapse" aria-labelledby="heading-<?php echo e($loop->index); ?>">
                    <div class="accordion-body p-0">
                        <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0" style="table-layout: fixed;">
                                        <thead class="table-light">
                                            <tr>
                                                <th style="width: 5%;" class="text-center">
                                                    <input type="checkbox" class="form-check-input checkAll-subject" title="Pilih semua di mapel ini">
                                                </th>
                                                <th style="width: 5%;">No</th>
                                                <th style="width: 15%;">Kelas / Sem</th>
                                                <th style="width: 35%;">Topik / Materi</th>
                                                <th style="width: 10%;" class="text-center">Pertemuan</th>
                                                <th style="width: 15%;">Model</th>
                                                <th style="width: 15%;" class="text-center">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                    <?php $__currentLoopData = $subjectModules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $modul): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td class="text-center">
                                            <input type="checkbox" class="form-check-input check-item" value="<?php echo e($modul->id); ?>">
                                        </td>
                                        <td><?php echo e($index + 1); ?></td>
                                        <td><?php echo e($modul->grade_level); ?> / <?php echo e($modul->semester); ?></td>
                                        <td class="fw-bold"><?php echo e($modul->topic ?? '-'); ?></td>
                                        <td class="text-center">
                                            <?php
                                                $isPraktikum = (strpos(strtolower($modul->model_learning ?? ''), 'praktikum') !== false || 
                                                                strpos(strtolower($modul->model_learning ?? ''), 'kerja bengkel') !== false);
                                            ?>

                                            <?php if($isPraktikum): ?>
                                                <span class="badge bg-warning text-dark"><?php echo e($modul->meeting_sequence); ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-info text-dark"><?php echo e($modul->meeting_sequence); ?></span>
                                            <?php endif; ?>
                                        </td>                                        
                                                <td><?php echo e($modul->model_learning ?? '-'); ?></td>
                                        <td class="text-nowrap">
                                            <button class="btn btn-sm btn-info text-white me-1" data-bs-toggle="modal" data-bs-target="#modalShow<?php echo e($modul->id); ?>" title="Lihat Detail">
                                                <i class="bi bi-eye-fill"></i>
                                            </button>
                                            <button class="btn btn-sm btn-warning text-white me-1" data-bs-toggle="modal" data-bs-target="#modalEdit<?php echo e($modul->id); ?>" title="Edit">
                                                <i class="bi bi-pencil-square"></i>
                                            </button>
                                            <a href="<?php echo e(route('modul.printSingle', $modul->id)); ?>" target="_blank" class="btn btn-sm btn-success text-white me-1" title="Cetak Modul">
                                                <i class="bi bi-printer-fill"></i>
                                            </a>
                                            <form action="<?php echo e(route('modul.destroy', $modul->id)); ?>" method="POST" class="d-inline" onsubmit="return confirm('Hapus modul ini?')">
                                                <?php echo csrf_field(); ?> <?php echo method_field('DELETE'); ?>
                                                <button class="btn btn-sm btn-outline-danger" title="Hapus"><i class="bi bi-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
            <div class="card shadow-sm border-0">
                <div class="card-body text-center py-5">
                    <p class="text-muted mb-0">Belum ada modul ajar yang dibuat.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>


<div class="modal fade" id="modalModul" tabindex="-1">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
             <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Form Input Modul Ajar</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
             <form action="<?php echo e(route('modul.store')); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <div class="modal-body bg-light">
                    <div class="container bg-white p-4 rounded shadow-sm" style="max-width: 1000px;">
                        
                        <h5 class="text-primary fw-bold mb-3 border-bottom pb-2">I. Identitas Modul</h5>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Mata Pelajaran</label>
                        		<select name="subject_id" id="selectMapel" class="form-select auto-mapel" required>
                                    <option value="">-- Pilih Mata Pelajaran --</option>
                                    <?php $__currentLoopData = $subjects; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($s->id); ?>"><?php echo e($s->name); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-4">
   								<label class="form-label fw-bold">Kelas</label>
    							<select name="grade_level" id="selectGrade" class="form-select auto-grade" required>
        							<option value="">-- Pilih Kelas --</option>
        							<option value="X">Kelas X</option>
       	 							<option value="XI">Kelas XI</option>
        							<option value="XII">Kelas XII</option>
    							</select>
							</div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Semester</label>
                                <select name="semester" class="form-select auto-semester">
                                    <option value="Ganjil">Ganjil</option>
                                    <option value="Genap">Genap</option>
                                </select>
                            </div>
                        </div>

                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Dimensi Profil Lulusan</label>
                            <div class="card p-3 bg-light border-0">
                                <div class="row">
                                    <?php $__currentLoopData = $refProfil; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $profil): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <div class="col-md-4 mb-2">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="profil_pelajar_pancasila[]" value="<?php echo e($profil); ?>" id="p_new_<?php echo e($loop->index); ?>">
                                                <label class="form-check-label" for="p_new_<?php echo e($loop->index); ?>"><?php echo e($profil); ?></label>
                                            </div>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            </div>
                        </div>

                        
                        <div class="row mb-3 bg-light p-3 rounded mx-1">
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Elemen</label><input type="text" name="elemen" class="form-control" placeholder="Contoh: Aljabar / Instalasi Motor"></div>
                            
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Pertemuan Ke-</label><input type="number" name="meeting_sequence" id="inputPertemuan" class="form-control auto-meeting" readonly placeholder="Pilih Model Pembelajaran..." required></div>
                            
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Jumlah JP</label><input type="number" name="allocation_jp" class="form-control" required></div>
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Durasi JP (Menit)</label><input type="number" name="duration_minutes" class="form-control" required></div>
                        </div>

                        
                        <h5 class="text-primary fw-bold mb-3 mt-4 border-bottom pb-2">II. Komponen Kurikulum</h5>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Capaian Pembelajaran (CP)</label>
                            <select id="selectCP" class="form-select"><option value="">-- Pilih Mata Pelajaran Terlebih Dahulu --</option></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Tujuan Pembelajaran (TP)</label>
                            <select name="learning_objective_id" id="selectTP" class="form-select" required><option value="">-- Pilih CP Terlebih Dahulu --</option></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Topik Pembelajaran</label>
                            <input type="text" name="topic" class="form-control" required>
                        </div>

                        
                        <h5 class="text-primary fw-bold mb-3 mt-4 border-bottom pb-2">III. Metodologi & Sarana</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Model Pembelajaran</label>
                                <select name="model_learning" id="selectModel" class="form-select auto-model">
                                    <option value="">--Pilih Model--</option>
                                    <?php $__currentLoopData = $refModels; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>"><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Metode</label>
                                <select name="method_learning" class="form-select">
                                    <option value="">--Pilih Metode--</option>
                                    <?php $__currentLoopData = $refMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>"><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Strategi Pembelajaran</label>
                                <select name="strategy_learning" class="form-select">
                                    <option value="">-- Pilih Strategi --</option>
                                    <?php $__currentLoopData = $refStrategies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($s); ?>"><?php echo e($s); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Pendekatan</label>
                                <select name="approach_learning" class="form-select">
                                    <option value="">--Pilih Pendekatan--</option>
                                    <?php $__currentLoopData = $refApproaches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>"><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Lingkungan</label>
                                <select name="learning_environment" class="form-select">
                                    <option value="">-- Pilih Lingkungan --</option>
                                    <?php $__currentLoopData = $refEnvironments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $e): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($e); ?>"><?php echo e($e); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Digital (TIK)</label>
                                <select name="digital_usage" class="form-select">
                                    <option value="">-- Pilih Media --</option>
                                    <?php $__currentLoopData = $refDigital; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($d); ?>"><?php echo e($d); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        
                        <div class="d-flex justify-content-between align-items-center mb-3 mt-4 border-bottom pb-2">
                            <h5 class="text-primary fw-bold mb-0">IV. Langkah Pembelajaran</h5>
                            <button type="button" class="btn btn-sm btn-ai-gradient shadow-sm" onclick="generateAI(this)">
                                <i class="bi bi-stars me-1"></i> Isi Otomatis dengan AI
                            </button>
                        </div>
                            
                        <div class="mb-3"><label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Awal</label><textarea name="activity_initial" class="form-control" rows="8" required></textarea></div>
                        <div class="mb-3">
                            <label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Inti</label>
                            <div class="mb-2"><small>Fase: Memahami / Mengamati</small></div><textarea name="activity_core_understand" class="form-control mb-3" rows="8"></textarea>
                            <div class="mb-2"><small>Fase: Mengaplikasi / Mencoba</small></div><textarea name="activity_core_apply" class="form-control mb-3" rows="8"></textarea>
                            <div class="mb-2"><small>Fase: Merefleksi / Mengasosiasi</small></div><textarea name="activity_core_reflect" class="form-control" rows="8"></textarea>
                        </div>
                        <div class="mb-3"><label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Penutup</label><textarea name="activity_closing" class="form-control" rows="8"></textarea></div>

                    </div>
                </div>
                <div class="modal-footer bg-white shadow-lg" style="position: sticky; bottom: 0;">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary px-5 fw-bold">SIMPAN MODUL</button>
                </div>
            </form>
        </div>
    </div>
</div>


<?php $__currentLoopData = $modules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $modul): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="modal fade" id="modalEdit<?php echo e($modul->id); ?>" tabindex="-1">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
             <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title">Edit Modul Ajar</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
             <form action="<?php echo e(route('modul.update', $modul->id)); ?>" method="POST">
                <?php echo csrf_field(); ?> <?php echo method_field('PUT'); ?>
                <div class="modal-body bg-light">
                    <div class="container bg-white p-4 rounded shadow-sm" style="max-width: 1000px;">
                        
                        <h5 class="text-primary fw-bold mb-3 border-bottom pb-2">I. Identitas Modul</h5>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Mata Pelajaran</label>
                                <select name="subject_id" class="form-select auto-mapel" required>
                                    <?php $__currentLoopData = $subjects; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($s->id); ?>" <?php echo e($modul->subject_id == $s->id ? 'selected' : ''); ?>><?php echo e($s->name); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Kelas</label>
                                <select name="grade_level" class="form-select auto-grade" required>
                                    <option value="X" <?php echo e($modul->grade_level == 'X' ? 'selected' : ''); ?>>Kelas X</option>
                                    <option value="XI" <?php echo e($modul->grade_level == 'XI' ? 'selected' : ''); ?>>Kelas XI</option>
                                    <option value="XII" <?php echo e($modul->grade_level == 'XII' ? 'selected' : ''); ?>>Kelas XII</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Semester</label>
                                <select name="semester" class="form-select auto-semester">
                                    <option value="Ganjil" <?php echo e($modul->semester == 'Ganjil' ? 'selected' : ''); ?>>Ganjil</option>
                                    <option value="Genap" <?php echo e($modul->semester == 'Genap' ? 'selected' : ''); ?>>Genap</option>
                                </select>
                            </div>
                        </div>

                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Dimensi Profil Lulusan</label>
                            <div class="card p-3 bg-light border-0">
                                <div class="row">
                                    <?php $__currentLoopData = $refProfil; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $profil): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <div class="col-md-4 mb-2">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="profil_pelajar_pancasila[]" value="<?php echo e($profil); ?>" id="p_edit_<?php echo e($modul->id); ?>_<?php echo e($loop->index); ?>"
                                                <?php echo e((is_array($modul->profil_pelajar_pancasila) && in_array($profil, $modul->profil_pelajar_pancasila)) ? 'checked' : ''); ?>>
                                                <label class="form-check-label" for="p_edit_<?php echo e($modul->id); ?>_<?php echo e($loop->index); ?>"><?php echo e($profil); ?></label>
                                            </div>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            </div>
                        </div>

                        
                        <div class="row mb-3 bg-light p-3 rounded mx-1">
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Elemen</label><input type="text" name="elemen" class="form-control" value="<?php echo e($modul->elemen); ?>"></div>
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Pertemuan Ke-</label><input type="number" name="meeting_sequence" class="form-control auto-meeting" value="<?php echo e($modul->meeting_sequence); ?>" required></div>
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Jumlah JP</label><input type="number" name="allocation_jp" class="form-control" value="<?php echo e($modul->allocation_jp); ?>"></div>
                            <div class="col-md-6 mb-2"><label class="form-label fw-bold">Durasi JP</label><input type="number" name="duration_minutes" class="form-control" value="<?php echo e($modul->duration_minutes); ?>"></div>
                        </div>

                        
                        <h5 class="text-primary fw-bold mb-3 mt-4 border-bottom pb-2">II. Komponen Kurikulum (Edit)</h5>
                        <div class="mb-3">
                            <label class="form-label text-muted fw-bold">CP - Saat Ini</label>
                            <textarea class="form-control bg-light" rows="2" readonly><?php echo e($modul->cp_text); ?></textarea>
                        </div>
                        <div class="mb-3">
                             <label class="form-label text-muted fw-bold">TP - Saat Ini</label>
                             <input type="hidden" name="learning_objective_id" value="<?php echo e($modul->learning_objective_id); ?>">
                             <textarea class="form-control bg-light tp-display-text" rows="2" readonly><?php echo e($modul->tp_text); ?></textarea>
                        </div>
                        <div class="mb-3"><label class="form-label fw-bold fw-bold">Topik Pembelajaran</label><input type="text" name="topic" class="form-control" value="<?php echo e($modul->topic); ?>" required></div>

                        
                        <h5 class="text-primary fw-bold mb-3 mt-4 border-bottom pb-2">III. Metodologi & Sarana (Edit)</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Model</label>
                                <select name="model_learning" class="form-select auto-model">
                                    <option value="">Pilih Model...</option>
                                    <?php $__currentLoopData = $refModels; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>" <?php echo e($modul->model_learning == $m ? 'selected' : ''); ?>><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Metode</label>
                                <select name="method_learning" class="form-select">
                                    <option value="">Pilih Metode...</option>
                                    <?php $__currentLoopData = $refMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>" <?php echo e($modul->method_learning == $m ? 'selected' : ''); ?>><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Strategi</label>
                                <select name="strategy_learning" class="form-select">
                                    <option value="">-- Pilih Strategi --</option>
                                    <?php $__currentLoopData = $refStrategies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($s); ?>" <?php echo e($modul->strategy_learning == $s ? 'selected' : ''); ?>><?php echo e($s); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Pendekatan</label>
                                <select name="approach_learning" class="form-select">
                                    <option value="">Pilih Pendekatan...</option>
                                    <?php $__currentLoopData = $refApproaches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($m); ?>" <?php echo e($modul->approach_learning == $m ? 'selected' : ''); ?>><?php echo e($m); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Lingkungan</label>
                                <select name="learning_environment" class="form-select">
                                    <option value="">-- Pilih Lingkungan --</option>
                                    <?php $__currentLoopData = $refEnvironments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $e): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($e); ?>" <?php echo e($modul->learning_environment == $e ? 'selected' : ''); ?>><?php echo e($e); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Digital (TIK)</label>
                                <select name="digital_usage" class="form-select">
                                    <option value="">-- Pilih Media --</option>
                                    <?php $__currentLoopData = $refDigital; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <option value="<?php echo e($d); ?>" <?php echo e($modul->digital_usage == $d ? 'selected' : ''); ?>><?php echo e($d); ?></option> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        
                        <div class="d-flex justify-content-between align-items-center mb-3 mt-4 border-bottom pb-2">
                            <h5 class="text-primary fw-bold mb-0">IV. Langkah Pembelajaran (Edit)</h5>
                            <button type="button" class="btn btn-sm btn-ai-gradient shadow-sm" onclick="generateAI(this)">
                                <i class="bi bi-stars me-1"></i> Perbaiki dengan AI
                            </button>
                        </div>
                        <div class="mb-3"><label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Awal</label><textarea name="activity_initial" class="form-control" rows="8" required><?php echo e($modul->activity_initial); ?></textarea></div>
                        <div class="mb-3">
                            <label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Inti</label>
                            <div class="mb-2"><small>Fase: Memahami / Mengamati</small></div><textarea name="activity_core_understand" class="form-control mb-3" rows="8"><?php echo e($modul->activity_core_understand); ?></textarea>
                            <div class="mb-2"><small>Fase: Mengaplikasi / Mencoba</small></div><textarea name="activity_core_apply" class="form-control mb-3" rows="8"><?php echo e($modul->activity_core_apply); ?></textarea>
                            <div class="mb-2"><small>Fase: Merefleksi / Mengasosiasi</small></div><textarea name="activity_core_reflect" class="form-control" rows="8"><?php echo e($modul->activity_core_reflect); ?></textarea>
                        </div>
                        <div class="mb-3"><label class="form-label fw-bold bg-light w-100 p-2 border">Kegiatan Penutup</label><textarea name="activity_closing" class="form-control" rows="8"><?php echo e($modul->activity_closing); ?></textarea></div>

                    </div>
                </div>
                <div class="modal-footer bg-white shadow-lg">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning px-5 fw-bold">UPDATE MODUL</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


<?php $__currentLoopData = $modules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $modul): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="modal fade" id="modalShow<?php echo e($modul->id); ?>" tabindex="-1">
    <div class="modal-dialog modal-xl" id="dialogShow<?php echo e($modul->id); ?>">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="bi bi-file-text"></i> Pratinjau Modul Ajar</h5>
                <div>
                    <button type="button" class="btn btn-sm btn-light text-info fw-bold me-2" onclick="toggleFullscreenModal('<?php echo e($modul->id); ?>')" title="Layar Penuh">
                        <i class="bi bi-arrows-fullscreen"></i> Fullscreen
                    </button>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
            </div>
            <div class="modal-body bg-light">
                <div class="container paper-view">
                    
                    <div class="paper-header">
                        <h3>MODUL AJAR</h3>
                        <h5><?php echo e($modul->subject->name); ?> - Kelas <?php echo e($modul->grade_level); ?></h5>
                    </div>

                    
                    <div class="section-title">I. INFORMASI UMUM</div>
                    <div class="info-row"><div class="info-label">Penyusun</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->user->name ?? '-'); ?></div></div>
                    <div class="info-row"><div class="info-label">NIP</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->user->nip ?? '-'); ?></div></div>
                    <div class="info-row"><div class="info-label">Topik</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->topic); ?></div></div>
                    <div class="info-row"><div class="info-label">Alokasi Waktu</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->allocation_jp); ?> JP x <?php echo e($modul->duration_minutes); ?> Menit (Pertemuan ke-<?php echo e($modul->meeting_sequence); ?>)</div></div>
                    <div class="info-row"><div class="info-label">Dimensi Profil Lulusan</div><div class="info-sep">:</div><div class="info-val">
                        <?php if(is_array($modul->profil_pelajar_pancasila)): ?> <?php echo e(implode(', ', $modul->profil_pelajar_pancasila)); ?> <?php else: ?> - <?php endif; ?>
                    </div></div>

                    
                    <div class="section-title">II. METODOLOGI PEMBELAJARAN</div>
                    <div class="info-row"><div class="info-label">Model</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->model_learning); ?></div></div>
                    <div class="info-row"><div class="info-label">Metode</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->method_learning); ?></div></div>
                    <div class="info-row"><div class="info-label">Strategi</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->strategy_learning); ?></div></div>
                    <div class="info-row"><div class="info-label">Pendekatan</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->approach_learning); ?></div></div>
                    <div class="info-row"><div class="info-label">Media (TIK)</div><div class="info-sep">:</div><div class="info-val"><?php echo e($modul->digital_usage); ?></div></div>

                    
                    <div class="section-title">III. KOMPONEN INTI</div>
                    <div class="fw-bold mb-1">A. Capaian Pembelajaran (CP)</div>
                    <div class="formatted-text mb-3"><?php echo e($modul->cp_text); ?></div>
                    <div class="fw-bold mb-1">B. Tujuan Pembelajaran (TP)</div>
                    <div class="formatted-text mb-3"><?php echo e($modul->tp_text); ?></div>
                    
                    
                    <div class="section-title">IV. LANGKAH PEMBELAJARAN</div>

                    <div class="fw-bold bg-light p-1 border mb-2">1. Kegiatan Pendahuluan</div>
                    <div class="indent-block mb-3">
                        <?php echo nl2br(e(str_replace('**', '', $modul->activity_initial))); ?>

                    </div>

                    <div class="fw-bold bg-light p-1 border mb-2">2. Kegiatan Inti</div>
                    <div>
                        <div class="sub-point-title">a. Fase Memahami / Mengamati:</div>
                        <div class="sub-point-content">
                            <?php echo nl2br(e(str_replace('**', '', $modul->activity_core_understand))); ?>

                        </div>
                        <div class="sub-point-title">b. Fase Mencoba / Mengaplikasi:</div>
                        <div class="sub-point-content">
                            <?php echo nl2br(e(str_replace('**', '', $modul->activity_core_apply))); ?>

                        </div>
                        <div class="sub-point-title">c. Fase Merefleksi / Mengasosiasi:</div>
                        <div class="sub-point-content">
                            <?php echo nl2br(e(str_replace('**', '', $modul->activity_core_reflect))); ?>

                        </div>
                    </div>

                    <div class="fw-bold bg-light p-1 border mb-2 mt-3">3. Kegiatan Penutup</div>
                    <div class="indent-block mb-3">
                        <?php echo nl2br(e(str_replace('**', '', $modul->activity_closing))); ?>

                    </div>

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


<div class="modal fade" id="modalCetak" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold"><i class="bi bi-printer"></i> Cetak Modul Ajar</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?php echo e(route('modul.print')); ?>" method="POST" target="_blank">
                <?php echo csrf_field(); ?>
                <div class="modal-body">
                    <p class="mb-3">Modul yang dipilih akan digabungkan menjadi satu file PDF.</p>
                    <div id="hiddenInputsContainer"></div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Tanggal Cetak</label>
                        <input type="date" name="print_date" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" required>
                    </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" onclick="setTimeout(() => location.reload(), 2000)">
                        <i class="bi bi-printer-fill me-1"></i> Cetak Sekarang
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // --- 1. FUNGSI TOGGLE FULLSCREEN MODAL ---
    function toggleFullscreenModal(id) {
        let dialog = document.getElementById('dialogShow' + id);
        if(dialog) {
            dialog.classList.toggle('modal-fullscreen-custom');
            dialog.classList.toggle('modal-xl'); 
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        
        // --- 2. SELECT ALL PER MAPEL ---
        let checkAllBtns = document.querySelectorAll('.checkAll-subject');
        checkAllBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                let table = this.closest('table');
                let checkboxes = table.querySelectorAll('.check-item');
                checkboxes.forEach((checkbox) => { checkbox.checked = this.checked; });
            });
        });

        // --- 3. DEPENDENT DROPDOWN CP/TP ---
        let mapelSelect = document.getElementById('selectMapel');
        if(mapelSelect){
            mapelSelect.addEventListener('change', function() {
                let subjectId = this.value;
                let cpSelect = document.getElementById('selectCP');
                let tpSelect = document.getElementById('selectTP');
                
                cpSelect.innerHTML = '<option value="">Sedang memuat...</option>';
                tpSelect.innerHTML = '<option value="">-- Pilih CP Terlebih Dahulu --</option>';
                cpSelect.disabled = true; tpSelect.disabled = true;

                if(subjectId) {
                    let url = "<?php echo e(route('api.getCP', ':id')); ?>".replace(':id', subjectId);
                    fetch(url)
                        .then(res => res.json())
                        .then(data => {
                            cpSelect.innerHTML = '<option value="">-- Pilih Capaian Pembelajaran --</option>';
                            if(data.length > 0) {
                                data.forEach(item => {
                                    let option = document.createElement('option');
                                    option.value = item.learning_outcome; 
                                    option.text = item.learning_outcome.substring(0, 100) + '... (Fase ' + item.phase + ')';
                                    cpSelect.appendChild(option);
                                });
                                cpSelect.disabled = false;
                            } else {
                                cpSelect.innerHTML = '<option value="">Data CP tidak ditemukan</option>';
                            }
                        })
                        .catch(err => {
                            console.error(err);
                            cpSelect.innerHTML = '<option value="">Gagal koneksi</option>';
                        });
                }
            });
        }

        let cpSelect = document.getElementById('selectCP');
        if(cpSelect){
            cpSelect.addEventListener('change', function() {
                let cpText = this.value;
                let subjectId = document.getElementById('selectMapel').value;
                let tpSelect = document.getElementById('selectTP');
                let csrfToken = document.querySelector('input[name="_token"]').value;

                tpSelect.innerHTML = '<option value="">Sedang memuat TP...</option>';
                tpSelect.disabled = true;

                if(cpText && subjectId) {
                    fetch("<?php echo e(route('api.getTP')); ?>", {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                        body: JSON.stringify({ cp_name: cpText, subject_id: subjectId })
                    })
                    .then(res => res.json())
                    .then(data => {
                        tpSelect.innerHTML = '<option value="">-- Pilih Tujuan Pembelajaran --</option>';
                        if(data.length > 0) {
                            data.forEach(item => {
                                let option = document.createElement('option');
                                option.value = item.id; 
                                option.text = item.objective_description;
                                tpSelect.appendChild(option);
                            });
                            tpSelect.disabled = false;
                        } else {
                            tpSelect.innerHTML = '<option value="">TP tidak ditemukan</option>';
                        }
                    })
                    .catch(err => console.error(err));
                }
            });
        }

        // --- 4. AUTO-FILL NOMOR PERTEMUAN (TEORI & PRAKTIK) ---
        function fetchNextMeeting(form) {
            let mapelSelect = form.querySelector('.auto-mapel');
            let gradeSelect = form.querySelector('.auto-grade');
            let semesterSelect = form.querySelector('.auto-semester');
            let modelSelect = form.querySelector('.auto-model');
            let meetingInput = form.querySelector('.auto-meeting');

            if (!mapelSelect || !gradeSelect || !semesterSelect || !meetingInput || !modelSelect) return;

            let subjectId = mapelSelect.value;
            let gradeLevel = gradeSelect.value;
            let semester = semesterSelect.value;
            let modelLearning = modelSelect.value;

            if (subjectId && gradeLevel && semester && modelLearning !== "") {
                let oldVal = meetingInput.value;
                meetingInput.placeholder = "Memuat...";
                meetingInput.value = ""; 

                let url = `<?php echo e(route('api.getNextMeeting')); ?>?subject_id=${subjectId}&grade_level=${gradeLevel}&semester=${semester}&model_learning=${encodeURIComponent(modelLearning)}`;

                fetch(url)
                    .then(res => res.json())
                    .then(data => {
                        meetingInput.value = data.next_meeting;
                    })
                    .catch(err => {
                        console.error("Gagal mengambil data urutan pertemuan:", err);
                        meetingInput.placeholder = "Gagal memuat";
                        meetingInput.value = oldVal; 
                    });
            } else {
                meetingInput.value = "";
                meetingInput.placeholder = "Pilih Model Pembelajaran...";
            }
        }

        // Event Listener untuk mendeteksi perubahan dropdown
        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('auto-mapel') || 
                e.target.classList.contains('auto-grade') || 
                e.target.classList.contains('auto-semester') || 
                e.target.classList.contains('auto-model')) {
                
                let parentForm = e.target.closest('form');
                if(parentForm) {
                    fetchNextMeeting(parentForm);
                }
            }
        });

        // --- 5. SHOW MODAL ON ERROR ---
        <?php if($errors->any()): ?>
            var myModal = new bootstrap.Modal(document.getElementById('modalModul'));
            myModal.show();
        <?php endif; ?>
    });

    // --- 6. FUNGSI CETAK BULK ---
    function openPrintModal() {
        let selectedIds = [];
        document.querySelectorAll('.check-item:checked').forEach((el) => { selectedIds.push(el.value); });
        
        if (selectedIds.length === 0) { alert("Harap pilih minimal satu modul!"); return; }
        
        let container = document.getElementById('hiddenInputsContainer');
        container.innerHTML = ''; 
        selectedIds.forEach(id => {
            let input = document.createElement('input');
            input.type = 'hidden'; input.name = 'module_ids[]'; input.value = id;
            container.appendChild(input);
        });
        new bootstrap.Modal(document.getElementById('modalCetak')).show();
    }

// --- 5. FUNGSI AI GENERATOR ---
function generateAI(btn) {
    const originalText = btn.innerHTML;
    const form = btn.closest('form');
    
    const getValue = (name) => {
        let el = form.querySelector(`[name="${name}"]`);
        return el ? (el.value || '-') : '-';
    };

    const getSelectText = (name) => {
        let el = form.querySelector(`select[name="${name}"]`);
        if (!el || el.selectedIndex === -1) return '-';
        return el.options[el.selectedIndex].text;
    };

    const getCheckedValues = (name) => {
        let checkboxes = form.querySelectorAll(`input[name="${name}"]:checked`);
        return Array.from(checkboxes).map(cb => cb.value).join(', ') || '-';
    };

    let tpText = '';
    const tpSelect = form.querySelector('select[name="learning_objective_id"]');
    if(tpSelect && !tpSelect.disabled && tpSelect.value) {
        tpText = tpSelect.options[tpSelect.selectedIndex].text;
    } else {
        const tpDisplay = form.querySelector('.tp-display-text'); 
        if(tpDisplay) tpText = tpDisplay.value;
    }

    const dataKirim = {
        subject_name: getSelectText('subject_id'),
        topic: getValue('topic'),
        elemen: getValue('elemen'),
        meeting_sequence: getValue('meeting_sequence'),
        allocation_jp: getValue('allocation_jp'),
        duration_minutes: getValue('duration_minutes'),
        model_learning: getValue('model_learning'),
        method_learning: getValue('method_learning'),
        strategy_learning: getValue('strategy_learning'),
        approach_learning: getValue('approach_learning'),
        learning_environment: getValue('learning_environment'), 
        digital_usage: getValue('digital_usage'),
        profil_pelajar_pancasila: getCheckedValues('profil_pelajar_pancasila[]'),
        tp_text: tpText
    };

    if(dataKirim.topic === '-' || dataKirim.topic === '') {
        alert("⚠️ Mohon isi Topik Pembelajaran terlebih dahulu.");
        return;
    }

    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Sedang Berpikir...';
    btn.disabled = true;

    // Ambil CSRF Token
    const csrfToken = form.querySelector('input[name="_token"]').value;

    // Tembak ke API Controller (Bukan ai-logic.php lagi)
    fetch("<?php echo e(route('api.generateAI')); ?>", { 
        method: "POST",
        headers: { 
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": csrfToken
        },
        body: JSON.stringify(dataKirim)
    })
    .then(async response => {
        const text = await response.text();
        console.log("RAW RESPONSE SERVER:", text); 

        if (!response.ok) {
            let errorMsg = "Terjadi kesalahan pada server.";
            try {
                let errJson = JSON.parse(text);
                errorMsg = errJson.error || errorMsg;
            } catch (e) {}
            throw new Error(errorMsg);
        }

        try { 
            return JSON.parse(text); 
        } catch (e) { 
            throw new Error("Respon Server Rusak (Bukan JSON). Cek Console F12."); 
        }
    })
    .then(res => {
        if(res.error) {
            alert("❌ ERROR SERVER:\n" + res.error);
        } else {
            const formatContent = (val) => {
                if (!val) return '';
                if (typeof val === 'object') {
                    if(Array.isArray(val)) return val.join('\n');
                    return JSON.stringify(val); 
                }
                let str = String(val);
                str = str.replace(/[\[\]"{}]/g, ''); 
                str = str.replace(/\\n/g, '\n');      
                str = str.replace(/([^\n])\s(\d+\.)/g, '$1\n$2')
                        .replace(/([^\n])\s([a-z]\.)/g, '$1\n$2');
                return str.trim();
            };

            const setVal = (name, val) => {
                let el = form.querySelector(`textarea[name="${name}"]`);
                if(el) el.value = formatContent(val);
            };

            setVal('activity_initial', res.activity_initial);
            setVal('activity_core_understand', res.activity_core_understand);
            setVal('activity_core_apply', res.activity_core_apply);
            setVal('activity_core_reflect', res.activity_core_reflect);
            setVal('activity_closing', res.activity_closing);
            
            alert("✅ SUKSES! Modul berhasil dibuat.");
        }
    })
    .catch(err => { 
        console.error(err);
        alert("⚠️ GAGAL: " + err.message); 
    })
    .finally(() => {
        btn.innerHTML = originalText;
        btn.disabled = false;
    });
}
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/vol15_7/infinityfree.com/if0_40829333/htdocs/resources/views/pages/perangkat/modul/index.blade.php ENDPATH**/ ?>