<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-4">
    <!-- Welcome Banner Premium -->
    <div class="card border-0 shadow-sm overflow-hidden mb-4" style="border-radius: 16px;">
        <div class="p-4 p-md-5 text-white position-relative" style="background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%);">
            <div class="position-absolute top-0 end-0 p-4 opacity-10 d-none d-md-block" style="font-size: 8rem; pointer-events: none;">
                <i class="bi bi-cpu"></i>
            </div>
            <div class="row align-items-center position-relative">
                <div class="col-md-8">
                    <span class="badge bg-white bg-opacity-20 text-white mb-2 px-3 py-2" style="border-radius: 30px; backdrop-filter: blur(5px); font-size: 0.8rem;">
                        <i class="bi bi-cpu-fill me-1"></i> AI Learning Co-pilot
                    </span>
                    <h2 class="fw-bold mb-1">Penyusunan Perangkat Pembelajaran</h2>
                    <p class="mb-0 text-white-50 leading-relaxed">Rancang program semester, pekan efektif, alur pembelajaran, hingga modul ajar lengkap berbasis Kurikulum Merdeka secara modular.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Active Device Selector Card -->
    <div class="card border-0 shadow-sm mb-4" style="border-radius: 14px; border-left: 4px solid #4f46e5;">
        <div class="card-body p-4 d-flex flex-wrap align-items-center justify-content-between gap-3">
            <div class="d-flex align-items-center gap-3">
                <div class="p-3 bg-primary bg-opacity-10 text-primary rounded-3">
                    <i class="bi bi-journal-bookmark-fill fs-4"></i>
                </div>
                <div>
                    <span class="text-muted small d-block">Mata Pelajaran & Kelas Aktif:</span>
                    <?php if ($selectedDevice): ?>
                        <span class="fw-bold text-dark fs-5">
                            <?= esc($selectedDevice['subject_name']) ?> &bull; Kelas <?= esc($selectedDevice['grade_name']) ?> (Fase <?= esc($selectedDevice['phase']) ?>)
                        </span>
                        <div class="text-muted small mt-1">
                            <i class="bi bi-calendar3 me-1"></i> Tahun Ajaran <?= esc($selectedDevice['academic_year_name']) ?> &bull;
                            <?php if ($selectedDevice['school_type'] === 'madrasah'): ?>
                                <span class="text-success"><i class="bi bi-moon-stars-fill ms-1 me-1"></i> KMA/Madrasah</span>
                            <?php else: ?>
                                <span class="text-primary"><i class="bi bi-flag-fill ms-1 me-1"></i> Sekolah Umum</span>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <span class="text-danger fw-bold fs-6">Belum ada perangkat pembelajaran yang aktif. Silakan pilih atau buat setup baru!</span>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="d-flex align-items-center gap-2 ms-auto w-100 w-md-auto mt-3 mt-md-0">
                <select class="form-select border-light-subtle shadow-sm" id="selectAcademicYear" style="min-width: 160px; border-radius: 8px;">
                    <?php foreach ($academicYears as $year): ?>
                        <option value="<?= $year['id'] ?>" <?= ($year['id'] == $selectedYearId) ? 'selected' : '' ?>>
                            TA <?= esc($year['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <?php if (!empty($devices)): ?>
                    <select class="form-select border-light-subtle shadow-sm" id="selectDevice" style="min-width: 250px; border-radius: 8px;">
                        <?php foreach ($devices as $d): ?>
                            <option value="<?= $d['id'] ?>" <?= ($d['id'] == $selectedDeviceId) ? 'selected' : '' ?>>
                                <?= esc($d['subject_name']) ?> (Kelas <?= esc($d['grade_name']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                <?php endif; ?>


                <a href="/guru/learning-devices/create" class="btn btn-primary fw-bold px-3 shadow-sm d-flex align-items-center gap-1" style="border-radius: 8px;">
                    <i class="bi bi-plus-lg"></i> Setup Baru
                </a>
                
                <?php if ($selectedDevice): ?>
                    <form action="/guru/learning-devices/delete/<?= $selectedDevice['id'] ?>" method="post" class="d-inline" onsubmit="return confirm('Apakah Anda yakin ingin menghapus seluruh draf perangkat pembelajaran untuk kelas ini?')">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-outline-danger p-2" style="border-radius: 8px;" title="Hapus Perangkat Aktif">
                            <i class="bi bi-trash3"></i>
                        </button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Alert Flash Message -->
    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 py-3 mb-4 shadow-sm" role="alert" style="background-color: #d1e7dd; color: #0f5132; border-radius: 12px;">
            <i class="bi bi-check-circle-fill me-2 fs-5"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 py-3 mb-4 shadow-sm" role="alert" style="background-color: #f8d7da; color: #842029; border-radius: 12px;">
            <i class="bi bi-exclamation-triangle-fill me-2 fs-5"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- Grid Menu Cards -->
    <div class="row g-4">
        <!-- Card 1: Rencana Pekan Efektif (RPE) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-orange-light text-orange rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-calendar-event fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">1. RPE (Rincian Pekan Efektif)</h5>
                        <p class="text-muted small mb-4 text-justify">Rencana Pekan Efektif: Analisis kalender pendidikan sekolah/madrasah dan hitung alokasi pekan efektif mengajar.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/rpe/<?= $selectedDeviceId ?>" class="btn btn-orange w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka RPE <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka RPE <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 2: CP (Capaian Pembelajaran) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-primary bg-opacity-10 text-primary rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-file-earmark-ruled fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">2. CP (Capaian Pembelajaran)</h5>
                        <p class="text-muted small mb-4 text-justify">Capaian Pembelajaran: Tinjau, atur, dan sesuaikan teks kompetensi target kurikulum secara mandiri.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/cp/<?= $selectedDeviceId ?>" class="btn btn-primary w-100 py-2 fw-semibold rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka CP <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka CP <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 3: TP (Tujuan Pembelajaran) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-info bg-opacity-10 text-info rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-file-earmark-text fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">3. TP (Tujuan Pembelajaran)</h5>
                        <p class="text-muted small mb-4 text-justify">Tujuan Pembelajaran: Rumuskan capaian kompetensi dan ruang lingkup materi spesifik berbasis analisis CP.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/tp/<?= $selectedDeviceId ?>" class="btn btn-info w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka TP <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka TP <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 4: ATP (Alur Tujuan Pembelajaran) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-success bg-opacity-10 text-success rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-diagram-3 fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">4. ATP (Alur Tujuan Pembelajaran)</h5>
                        <p class="text-muted small mb-4 text-justify">Alur Tujuan Pembelajaran: Urutkan rumusan TP secara logis dan runtut secara kronologis menggunakan drag & drop.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/atp/<?= $selectedDeviceId ?>" class="btn btn-success w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka ATP <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka ATP <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 5: PROTA (Program Tahunan) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-teal-light text-teal rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-calendar-range fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">5. PROTA (Program Tahunan)</h5>
                        <p class="text-muted small mb-4 text-justify">Program Tahunan: Distribusikan alokasi jam pelajaran (JP) efektif untuk masing-masing TP sepanjang tahun ajaran.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/prota/<?= $selectedDeviceId ?>" class="btn btn-teal w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka PROTA <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka PROTA <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 6: PROMES (Program Semester) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-indigo-light text-indigo rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-calendar-check fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">6. PROMES (Program Semester)</h5>
                        <p class="text-muted small mb-4 text-justify">Program Semester: Petakan rincian penyajian materi pembelajaran mingguan pada setiap bulan dalam semester berjalan.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/promes/<?= $selectedDeviceId ?>" class="btn btn-indigo w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka PROMES <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka PROMES <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 7: KKTP (Kriteria Ketercapaian TP) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-purple-light text-purple rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-bullseye fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">7. KKTP (Kriteria Ketercapaian TP)</h5>
                        <p class="text-muted small mb-4 text-justify">Kriteria Ketercapaian TP: Tentukan instrumen dan kriteria ketuntasan ketercapaian tujuan pembelajaran.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/kktp/<?= $selectedDeviceId ?>" class="btn btn-purple w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1" style="background-color: #6f42c1; border-color: #6f42c1;">
                                Buka KKTP <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka KKTP <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 8: RPM (Rencana Pembelajaran Madrasah / Modul Ajar) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-crimson-light text-crimson rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-journal-bookmark fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">8. RPM / Modul Ajar</h5>
                        <p class="text-muted small mb-4 text-justify">Rencana Pelaksanaan Mengajar: Susun draf Modul Ajar/RPP Kurikulum Merdeka lengkap berbasis AI per topik pembelajaran.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/rpm/<?= $selectedDeviceId ?>" class="btn btn-crimson w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Buka RPM <i class="bi bi-arrow-right"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Buka RPM <i class="bi bi-arrow-right"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 9: Pratinjau & Cetak Terpadu (A4) -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-success bg-opacity-10 text-success rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-printer fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">9. Pratinjau & Cetak (A4)</h5>
                        <p class="text-muted small mb-4 text-justify">Pratinjau & Cetak Terpadu: Cetak atau lihat seluruh dokumen administrasi mengajar Anda secara teratur dalam format kertas A4.</p>
                    </div>
                    <div>
                        <?php if ($selectedDeviceId): ?>
                            <a href="/guru/learning-devices/preview-all/<?= $selectedDeviceId ?>" target="_blank" class="btn btn-success w-100 py-2 fw-semibold text-white rounded-2 d-flex align-items-center justify-content-center gap-1">
                                Pratinjau & Cetak Terpadu <i class="bi bi-printer-fill"></i>
                            </a>
                        <?php else: ?>
                            <button class="btn btn-secondary w-100 py-2 fw-semibold rounded-2 disabled-btn-hint">
                                Pratinjau & Cetak Terpadu <i class="bi bi-printer-fill"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 10: Setting API Key AI -->
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 border-0 shadow-sm rounded-3 transition-all hover-translate bg-white">
                <div class="card-body p-4 d-flex flex-column justify-content-between">
                    <div>
                        <div class="icon-wrapper mb-3 bg-primary bg-opacity-10 text-primary rounded-3 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                            <i class="bi bi-key-fill fs-4"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1">10. Setting API Key AI</h5>
                        <p class="text-muted small mb-2 text-justify">Atur API Key pribadi Anda untuk menggunakan AI Co-pilot. Pilih provider Gemini atau OpenAI.</p>
                        <div class="mb-3">
                            <div class="d-flex align-items-center gap-2">
                                <select class="form-select form-select-sm border-light-subtle shadow-sm" id="apiProviderSelect" style="max-width: 140px; border-radius: 6px;">
                                    <option value="gemini" <?= ($teacher['ai_provider'] ?? 'gemini') == 'gemini' ? 'selected' : '' ?>>Gemini</option>
                                    <option value="openai" <?= ($teacher['ai_provider'] ?? '') == 'openai' ? 'selected' : '' ?>>OpenAI</option>
                                </select>
                                <span class="text-muted" style="font-size: 0.7rem;">
                                    <?= !empty($teacher['ai_api_key']) ? '<i class="bi bi-check-circle-fill text-success"></i> Key aktif' : '<i class="bi bi-exclamation-circle-fill text-warning"></i> Key kosong' ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-primary w-100 py-2 fw-semibold rounded-2 d-flex align-items-center justify-content-center gap-1" data-bs-toggle="modal" data-bs-target="#apiKeyModal">
                                <i class="bi bi-gear"></i> Atur Key
                            </button>
                            <button type="button" class="btn btn-outline-secondary py-2 fw-semibold rounded-2" id="btnResetApiKey" title="Reset ke API Key Admin">
                                <i class="bi bi-arrow-counterclockwise"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Dialog Information KKTP / Rubrik -->
<div class="modal fade" id="infoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow" style="border-radius: 12px;">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold text-dark" id="infoModalTitle">Informasi Modul</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body py-3">
                <p id="infoModalBody" class="text-muted small leading-relaxed mb-0"></p>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-primary btn-sm px-4 fw-semibold" data-bs-dismiss="modal" style="border-radius: 6px;">Mengerti</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal Dialog API Key AI Mandiri -->
<div class="modal fade" id="apiKeyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow" style="border-radius: 12px;">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold text-dark"><i class="bi bi-key text-primary me-1"></i> API Key AI Mandiri</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body py-3">
                <p class="text-muted small leading-relaxed mb-3">
                    Masukkan API Key pribadi Anda. Jika dikosongkan, sistem akan otomatis menggunakan API Key global dari Admin.
                </p>
                <form id="apiKeyForm">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label for="apiProviderSelectModal" class="form-label small fw-semibold text-muted">Provider AI</label>
                        <select class="form-select form-control-sm" id="apiProviderSelectModal" name="ai_provider" style="border-radius: 6px;">
                            <option value="gemini" <?= ($teacher['ai_provider'] ?? 'gemini') == 'gemini' ? 'selected' : '' ?>>Gemini</option>
                            <option value="openai" <?= ($teacher['ai_provider'] ?? '') == 'openai' ? 'selected' : '' ?>>OpenAI (gpt-4o-mini)</option>
                        </select>
                    </div>
                    <div class="mb-3" id="apiKeyInputGroup">
                        <label for="ai_api_key_input" class="form-label small fw-semibold text-muted">API Key</label>
                        <input type="text" class="form-control form-control-sm" id="ai_api_key_input" name="ai_api_key" value="<?= esc($teacher['ai_api_key'] ?? '') ?>" placeholder="AIzaSy..." style="border-radius: 6px;">
                    </div>
                </form>
            </div>
            <div class="modal-footer border-0 pt-0 d-flex justify-content-between">
                <button type="button" class="btn btn-outline-danger btn-sm px-3 fw-semibold rounded-2" id="btnDeleteApiKey">Hapus Key</button>
                <button type="button" class="btn btn-primary btn-sm px-4 fw-semibold rounded-2" id="btnSaveApiKey">Simpan Key</button>
            </div>
        </div>
    </div>
</div>

<style>
.hover-translate {
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    border: 1px solid rgba(0, 0, 0, 0.05);
}
.hover-translate:hover {
    transform: translateY(-3px);
    box-shadow: 0 0.75rem 1.5rem rgba(0, 0, 0, 0.08) !important;
}
.leading-relaxed {
    line-height: 1.6;
}
.text-justify {
    text-align: justify;
}

/* Custom Purple Color Styles */
.bg-purple-light {
    background-color: rgba(111, 66, 193, 0.1);
}
.text-purple {
    color: #6f42c1;
}
.btn-outline-purple {
    color: #6f42c1;
    border-color: #6f42c1;
}
.btn-outline-purple:hover {
    background-color: #6f42c1;
    color: #fff;
}

/* Custom Orange Color Styles */
.bg-orange-light {
    background-color: rgba(253, 126, 20, 0.1);
}
.text-orange {
    color: #fd7e14;
}
.btn-orange {
    background-color: #fd7e14;
    border-color: #fd7e14;
    color: #fff;
}
.btn-orange:hover {
    background-color: #e0690d;
    border-color: #e0690d;
    color: #fff;
}

/* Custom Teal Color Styles */
.bg-teal-light {
    background-color: rgba(32, 201, 151, 0.1);
}
.text-teal {
    color: #20c997;
}
.btn-teal {
    background-color: #20c997;
    border-color: #20c997;
    color: #fff;
}
.btn-teal:hover {
    background-color: #199e76;
    border-color: #199e76;
    color: #fff;
}

/* Custom Indigo Color Styles */
.bg-indigo-light {
    background-color: rgba(102, 16, 242, 0.1);
}
.text-indigo {
    color: #6610f2;
}
.btn-indigo {
    background-color: #6610f2;
    border-color: #6610f2;
    color: #fff;
}
.btn-indigo:hover {
    background-color: #510bc4;
    border-color: #510bc4;
    color: #fff;
}

/* Custom Crimson Color Styles */
.bg-crimson-light {
    background-color: rgba(232, 62, 140, 0.1);
}
.text-crimson {
    color: #e83e8c;
}
.btn-crimson {
    background-color: #e83e8c;
    border-color: #e83e8c;
    color: #fff;
}
.btn-crimson:hover {
    background-color: #ca2570;
    border-color: #ca2570;
    color: #fff;
}
</style>

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Select Device change
    $('#selectDevice').on('change', function() {
        const id = $(this).val();
        const yearId = $('#selectAcademicYear').val() || '<?= $selectedYearId ?>';
        window.location.href = '/guru/learning-devices?academic_year_id=' + yearId + '&device_id=' + id;
    });

    // Select Academic Year change
    $('#selectAcademicYear').on('change', function() {
        const yearId = $(this).val();
        window.location.href = '/guru/learning-devices?academic_year_id=' + yearId;
    });

    // Save API Key
    $('#btnSaveApiKey').on('click', function() {
        const apiKey = $('#ai_api_key_input').val();
        const btn = $(this);
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Menyimpan...');
        
        $.ajax({
            url: '/guru/learning-devices/save-api-key',
            type: 'POST',
            data: $('#apiKeyForm').serialize(),
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: res.message,
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                    btn.prop('disabled', false).text('Simpan Key');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal menghubungi server.', 'error');
                btn.prop('disabled', false).text('Simpan Key');
            }
        });
    });

    // Delete API Key
    $('#btnDeleteApiKey').on('click', function() {
        $('#ai_api_key_input').val('');
        $('#apiKeyForm').append('<input type="hidden" name="reset_key" value="1">');
        $('#btnSaveApiKey').trigger('click');
    });

    // Sync provider select antara card dan modal
    $('#apiProviderSelect').on('change', function() {
        $('#apiProviderSelectModal').val($(this).val());
        updatePlaceholder();
    });
    $('#apiProviderSelectModal').on('change', function() {
        $('#apiProviderSelect').val($(this).val());
        updatePlaceholder();
    });

    function updatePlaceholder() {
        const provider = $('#apiProviderSelectModal').val();
        if (provider === 'openai') {
            $('#ai_api_key_input').attr('placeholder', 'sk-...');
        } else {
            $('#ai_api_key_input').attr('placeholder', 'AIzaSy...');
        }
    }
    updatePlaceholder();

    // Reset API Key ke default admin
    $('#btnResetApiKey').on('click', function() {
        Swal.fire({
            title: 'Reset API Key?',
            text: 'API Key pribadi akan dihapus. Sistem akan menggunakan key bawaan Admin.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#6c757d',
            cancelButtonColor: '#dc3545',
            confirmButtonText: 'Ya, Reset',
            cancelButtonText: 'Batal',
        }).then(function(result) {
            if (result.isConfirmed) {
                $('#ai_api_key_input').val('');
                $('#apiKeyForm').append('<input type="hidden" name="reset_key" value="1">');
                $('#btnSaveApiKey').trigger('click');
            }
        });
    });

    // Disabled buttons hint
    $('.disabled-btn-hint').on('click', function(e) {
        e.preventDefault();
        Swal.fire({
            icon: 'warning',
            title: 'Perangkat Belum Aktif',
            text: 'Silakan pilih perangkat pembelajaran aktif terlebih dahulu pada dropdown di bagian atas atau klik "Setup Baru" untuk membuat draf kelas baru.',
            confirmButtonColor: '#4f46e5'
        });
    });

    // Info KKTP
    $('.info-kktp-btn').on('click', function() {
        $('#infoModalTitle').text('Modul Kriteria Ketercapaian TP (KKTP)');
        $('#infoModalBody').html('Dalam Kurikulum Merdeka, <strong>Kriteria Ketercapaian Tujuan Pembelajaran (KKTP)</strong> tidak dibuat sebagai dokumen terpisah, melainkan dirancang secara spesifik dan melekat langsung di dalam masing-masing <strong>Modul Ajar (RPM / RPP)</strong>.<br><br>Anda dapat menyusun dan mengintegrasikan kriteria penilaian ini secara otomatis menggunakan bantuan AI saat men-generate Modul Ajar di menu <strong>RPM</strong> (Langkah ke-7).');
        const modal = new bootstrap.Modal(document.getElementById('infoModal'));
        modal.show();
    });

    // Info Rubrik
    $('.info-rubrik-btn').on('click', function() {
        $('#infoModalTitle').text('Modul Rubrik Penilaian');
        $('#infoModalBody').html('<strong>Rubrik Penilaian Asesmen</strong> (Diagnostik, Formatif, & Sumatif) merupakan bagian integral dari komponen inti <strong>Modul Ajar (RPM)</strong>.<br><br>Setiap kali Anda menggunakan AI untuk membuat draf Modul Ajar di menu <strong>RPM</strong>, instrumen beserta rubrik kriteria penilaian akan otomatis dianalisis dan disusun oleh AI Engine sesuai kebutuhan indikator TP.');
        const modal = new bootstrap.Modal(document.getElementById('infoModal'));
        modal.show();
    });
});
</script>
<?= $this->endSection() ?>

<?= $this->endSection() ?>
