<script>
    let biayaTetapCounter = 0;

    document.addEventListener('DOMContentLoaded', function() {
        lucide.createIcons();

        const namaKampusInput = document.querySelector('input[name="nama"]');
        if (namaKampusInput) {
            namaKampusInput.addEventListener('input', function() {
                this.value = this.value.toUpperCase();
            });
            if (namaKampusInput.value) {
                namaKampusInput.value = namaKampusInput.value.toUpperCase();
            }
        }

        // Load existing biaya tetap untuk edit
        <?php if(isset($bagiHasil['biaya']) && !empty($bagiHasil['biaya'])): ?>
            <?php $__currentLoopData = $bagiHasil['biaya']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $biaya): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                tambahBiayaTetap(
                    '<?php echo e($key); ?>',
                    '<?php echo e(addslashes($biaya['nama'] ?? ucfirst(str_replace('_', ' ', $key)))); ?>',
                    '<?php echo e($biaya['penanggung'] ?? 'kampus'); ?>',
                    <?php echo e($biaya['persen']['kampus'] ?? ($biaya['persen_kampus'] ?? 100)); ?>,
                    <?php echo e($biaya['persen']['k2'] ?? ($biaya['persen_k2'] ?? 0)); ?>,
                    <?php echo e($biaya['rupiah'] ?? 0); ?>

                );
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php else: ?>
            // Default biaya tetap: penanggung KAMPUS (100% kampus, 0% k2)
            tambahBiayaTetap('jaket', 'Jaket Almamater', 'kampus', 100, 0, 0);
        <?php endif; ?>

        // Load existing biaya formulir untuk edit
        <?php if(isset($biayaFormulir) && !empty($biayaFormulir)): ?>
            <?php $__currentLoopData = $biayaFormulir; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $jenjang => $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php
                    $total = $data['total'] ?? 0;
                    $penanggung = $data['penanggung'] ?? 'k2';
                    $persenKampus = $data['persen']['kampus'] ?? ($data['persen_kampus'] ?? 0);
                    $persenK2 = $data['persen']['k2'] ?? ($data['persen_k2'] ?? 100);
                ?>
                tambahBiayaFormulir('<?php echo e($jenjang); ?>', <?php echo e($total); ?>, '<?php echo e($penanggung); ?>',
                    <?php echo e($persenKampus); ?>, <?php echo e($persenK2); ?>);
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php else: ?>
            // Default biaya formulir: penanggung K2 (0% kampus, 100% k2)
            const defaultJenjang = ['D3', 'D4', 'S1', 'S2'];
            defaultJenjang.forEach(jenjang => {
                tambahBiayaFormulir(jenjang, 0, 'k2', 0, 100);
            });
        <?php endif; ?>
    });

    // ==================== BAGI HASIL UTAMA ====================
    function hitungTotalBagiHasil() {
        const kampus = parseFloat(document.getElementById('bagiHasilKampus')?.value) || 0;
        const k2 = parseFloat(document.getElementById('bagiHasilK2')?.value) || 0;
        const yayasan = parseFloat(document.getElementById('bagiHasilYayasan')?.value) || 0;
        const total = kampus + k2 + yayasan;

        const totalSpan = document.getElementById('totalBagiHasil');
        if (totalSpan) totalSpan.textContent = total.toFixed(2);

        const infoDiv = document.getElementById('totalBagiHasilInfo');
        if (infoDiv) {
            if (Math.abs(total - 100) < 0.01) {
                infoDiv.className = 'p-3 rounded-lg bg-green-100 dark:bg-green-900/20 text-green-700';
            } else {
                infoDiv.className = 'p-3 rounded-lg bg-yellow-100 dark:bg-yellow-900/20 text-yellow-700';
            }
        }

        updateAllSharingPersen(kampus, k2);
    }

    function updateAllSharingPersen(kampus, k2) {
        // Update biaya tetap yang sharing
        document.querySelectorAll('#biayaTetapContainer > div').forEach(item => {
            const penanggungSelect = item.querySelector('.biaya-penanggung');
            if (penanggungSelect && penanggungSelect.value === 'sharing') {
                const persenKampusInput = item.querySelector('.biaya-persen-kampus');
                const persenK2Input = item.querySelector('.biaya-persen-k2');
                if (persenKampusInput && !persenKampusInput.readOnly) persenKampusInput.value = kampus;
                if (persenK2Input && !persenK2Input.readOnly) persenK2Input.value = k2;
                updateBiayaTetapData();
            }
        });

        // Update biaya formulir yang sharing
        document.querySelectorAll('#biayaFormulirContainer > div').forEach(item => {
            const penanggungSelect = item.querySelector('.formulir-penanggung');
            if (penanggungSelect && penanggungSelect.value === 'sharing') {
                const persenKampusInput = item.querySelector('.formulir-persen-kampus');
                const persenK2Input = item.querySelector('.formulir-persen-k2');
                if (persenKampusInput && !persenKampusInput.readOnly) persenKampusInput.value = kampus;
                if (persenK2Input && !persenK2Input.readOnly) persenK2Input.value = k2;
                updateFormulirRupiahPreview(item);
                updateBiayaFormulirData();
            }
        });
    }

    // ==================== BIAYA TETAP ====================
    function tambahBiayaTetap(key = '', nama = '', penanggung = 'kampus', persenKampus = 100, persenK2 = 0, rupiah = 0) {
        const id = biayaTetapCounter++;
        const container = document.getElementById('biayaTetapContainer');
        if (!container) return;

        const biayaItem = document.createElement('div');
        biayaItem.className = 'border border-slate-200 dark:border-gray-700 rounded-lg p-5 mb-4 bg-white dark:bg-gray-800/50 hover:shadow-md transition-shadow';
        biayaItem.dataset.id = id;

        biayaItem.innerHTML = `
            <div class="flex justify-between items-center mb-4 pb-2 border-b border-slate-100 dark:border-gray-700">
                <div class="flex items-center gap-2">
                    <i data-lucide="package" class="w-4 h-4 text-violet-500"></i>
                    <h5 class="font-medium text-gray-900 dark:text-white">Komponen Biaya #${biayaTetapCounter}</h5>
                </div>
                <button type="button" onclick="hapusBiayaTetapItem(this)" class="text-red-500 hover:text-red-700 transition-colors p-1 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </div>
            <div class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Nama Biaya</label>
                        <input type="text" class="biaya-nama w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${escapeHtml(nama)}" placeholder="Contoh: Jaket, Buku, SPP" oninput="updateBiayaTetapData()">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Penanggung</label>
                        <select class="biaya-penanggung w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            onchange="togglePenanggungBiayaTetap(this, ${id})">
                            <option value="kampus" ${penanggung === 'kampus' ? 'selected' : ''}>Kampus (100%)</option>
                            <option value="k2" ${penanggung === 'k2' ? 'selected' : ''}>K2 (100%)</option>
                            <option value="sharing" ${penanggung === 'sharing' ? 'selected' : ''}>Sharing</option>
                        </select>
                    </div>
                </div>
                <div id="sharingSectionBiaya-${id}" class="grid grid-cols-2 gap-4 p-4 bg-slate-50 dark:bg-gray-800 rounded-lg border border-slate-200 dark:border-gray-700" style="${penanggung !== 'sharing' ? 'display: none;' : ''}">
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Kampus (%)</label>
                        <input type="number" class="biaya-persen-kampus w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${persenKampus}" min="0" max="100" step="0.1" oninput="updateBiayaTetapData()">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">K2 (%)</label>
                        <input type="number" class="biaya-persen-k2 w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${persenK2}" min="0" max="100" step="0.1" oninput="updateBiayaTetapData()">
                    </div>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Nominal</label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm">Rp</span>
                        <input type="text" class="biaya-rupiah-display w-full pl-10 pr-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${rupiah ? parseInt(rupiah).toLocaleString('id-ID') : ''}" placeholder="0" oninput="handleRupiahInput(this, 'biaya')">
                        <input type="hidden" class="biaya-rupiah-actual" value="${rupiah}">
                    </div>
                </div>
            </div>
        `;

        container.appendChild(biayaItem);
        if (typeof lucide !== 'undefined') lucide.createIcons();
        updateBiayaTetapData();
    }

    function handleRupiahInput(input, type) {
        let value = input.value.replace(/[^\d]/g, '');
        const actualInput = input.parentElement.querySelector(`.${type}-rupiah-actual`);
        if (actualInput) actualInput.value = value || 0;
        input.value = value ? parseInt(value).toLocaleString('id-ID') : '';
        if (type === 'biaya') updateBiayaTetapData();
        else updateBiayaFormulirData();
    }

    function hapusBiayaTetapItem(btn) {
        const item = btn.closest('#biayaTetapContainer > div');
        const remainingItems = document.querySelectorAll('#biayaTetapContainer > div');

        if (remainingItems.length <= 1) {
            Swal.fire({ icon: 'warning', title: 'Peringatan', text: 'Minimal harus ada 1 komponen biaya tetap!', confirmButtonColor: '#f59e0b' });
            return;
        }

        Swal.fire({
            title: 'Hapus Komponen?', text: 'Apakah Anda yakin ingin menghapus komponen biaya ini?', icon: 'question',
            showCancelButton: true, confirmButtonText: 'Ya, Hapus', cancelButtonText: 'Batal', confirmButtonColor: '#ef4444'
        }).then((result) => { if (result.isConfirmed) { item.remove(); updateBiayaTetapData(); updateNomorUrutBiayaTetap(); } });
    }

    function updateNomorUrutBiayaTetap() {
        document.querySelectorAll('#biayaTetapContainer > div').forEach((item, index) => {
            const header = item.querySelector('.flex.justify-between.items-center h5');
            if (header) header.textContent = `Komponen Biaya #${index + 1}`;
        });
    }

    function togglePenanggungBiayaTetap(select, id) {
        const sharingSection = document.getElementById(`sharingSectionBiaya-${id}`);
        const kampusInput = document.querySelector(`#sharingSectionBiaya-${id} .biaya-persen-kampus`);
        const k2Input = document.querySelector(`#sharingSectionBiaya-${id} .biaya-persen-k2`);

        if (select.value === 'sharing') {
            // Default sharing: 70% kampus, 30% k2
            if (sharingSection) sharingSection.style.display = 'grid';
            if (kampusInput) {
                if (kampusInput.value == 0 || kampusInput.value == '' || kampusInput.value == 100) {
                    kampusInput.value = 70;
                }
                kampusInput.readOnly = false;
            }
            if (k2Input) {
                if (k2Input.value == 0 || k2Input.value == '' || k2Input.value == 100) {
                    k2Input.value = 30;
                }
                k2Input.readOnly = false;
            }
        } else {
            if (sharingSection) sharingSection.style.display = 'none';
            if (select.value === 'kampus') {
                if (kampusInput) { kampusInput.value = 100; kampusInput.readOnly = true; }
                if (k2Input) { k2Input.value = 0; k2Input.readOnly = true; }
            } else if (select.value === 'k2') {
                if (kampusInput) { kampusInput.value = 0; kampusInput.readOnly = true; }
                if (k2Input) { k2Input.value = 100; k2Input.readOnly = true; }
            }
        }
        updateBiayaTetapData();
    }

    function updateBiayaTetapData() {
        const items = [];
        document.querySelectorAll('#biayaTetapContainer > div').forEach(item => {
            const penanggung = item.querySelector('.biaya-penanggung')?.value || 'kampus';
            let persenKampus = parseFloat(item.querySelector('.biaya-persen-kampus')?.value) || 0;
            let persenK2 = parseFloat(item.querySelector('.biaya-persen-k2')?.value) || 0;

            if (penanggung !== 'sharing') {
                if (penanggung === 'kampus') { persenKampus = 100; persenK2 = 0; }
                else { persenKampus = 0; persenK2 = 100; }
            } else {
                // Jika sharing dan persen kosong, set default 70/30
                if (persenKampus === 0 && persenK2 === 0) {
                    persenKampus = 70;
                    persenK2 = 30;
                }
            }

            const data = {
                nama: item.querySelector('.biaya-nama')?.value || '',
                penanggung: penanggung,
                persen_kampus: persenKampus,
                persen_k2: persenK2,
                rupiah: parseFloat(item.querySelector('.biaya-rupiah-actual')?.value) || 0
            };
            if (data.nama) items.push(data);
        });
        const biayaTetapInput = document.getElementById('biayaTetapInput');
        if (biayaTetapInput) biayaTetapInput.value = JSON.stringify(items);
    }

    // ==================== BIAYA FORMULIR (EXTENDABLE) ====================
    function tambahJenjangFormulir() {
        const jenjangInput = document.getElementById('jenjangBaruInput');
        let jenjang = jenjangInput?.value.trim().toUpperCase();

        if (!jenjang) {
            Swal.fire({
                icon: 'warning',
                title: 'Peringatan',
                text: 'Masukkan nama jenjang terlebih dahulu! (contoh: Profesi, Spesialis)',
                confirmButtonColor: '#f59e0b'
            });
            return;
        }

        jenjangInput.value = '';

        const container = document.getElementById('biayaFormulirContainer');
        if (container.querySelector(`[data-jenjang="${jenjang}"]`)) {
            Swal.fire({
                icon: 'warning',
                title: 'Peringatan',
                text: `Jenjang ${jenjang} sudah ada!`,
                confirmButtonColor: '#f59e0b'
            });
            return;
        }

        // Default untuk jenjang baru: penanggung K2 (0% kampus, 100% k2)
        tambahBiayaFormulir(jenjang, 0, 'k2', 0, 100);
        updateBiayaFormulirData();

        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: `Jenjang ${jenjang} berhasil ditambahkan`,
            showConfirmButton: false,
            timer: 1500
        });
    }

    function tambahBiayaFormulir(jenjang, total = 0, penanggung = 'k2', persenKampus = 0, persenK2 = 100) {
        const container = document.getElementById('biayaFormulirContainer');
        if (!container) return;

        const safeJenjang = jenjang.replace(/[^a-zA-Z0-9]/g, '_');
        const formulirItem = document.createElement('div');
        formulirItem.className = 'border border-slate-200 dark:border-gray-700 rounded-lg p-5 mb-4 bg-white dark:bg-gray-800/50 hover:shadow-md transition-shadow';
        formulirItem.dataset.jenjang = jenjang;

        formulirItem.innerHTML = `
            <div class="flex justify-between items-center mb-4 pb-2 border-b border-slate-100 dark:border-gray-700">
                <div class="flex items-center gap-2">
                    <i data-lucide="file-text" class="w-4 h-4 text-emerald-500"></i>
                    <h5 class="font-medium text-gray-900 dark:text-white">Formulir ${escapeHtml(jenjang)}</h5>
                </div>
                <div class="flex items-center gap-2">
                    <button type="button" onclick="toggleFormulirDetail(this)" class="text-slate-400 hover:text-slate-600 transition-colors">
                        <i data-lucide="chevron-down" class="w-4 h-4 transition-transform"></i>
                    </button>
                    <button type="button" onclick="hapusBiayaFormulirItem(this)" class="text-red-500 hover:text-red-700 transition-colors p-1 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
            <div class="formulir-detail space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Total Biaya (Rp)</label>
                        <div class="relative">
                            <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm">Rp</span>
                            <input type="text" class="formulir-total-display w-full pl-10 pr-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                                value="${total ? parseInt(total).toLocaleString('id-ID') : ''}" placeholder="0" oninput="handleFormulirTotalInput(this)">
                            <input type="hidden" class="formulir-total-actual" value="${total}">
                        </div>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Penanggung</label>
                        <select class="formulir-penanggung w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            onchange="togglePenanggungFormulir(this, '${escapeHtml(jenjang)}')">
                            <option value="kampus" ${penanggung === 'kampus' ? 'selected' : ''}>Kampus (100%)</option>
                            <option value="k2" ${penanggung === 'k2' ? 'selected' : ''}>K2 (100%)</option>
                            <option value="sharing" ${penanggung === 'sharing' ? 'selected' : ''}>Sharing</option>
                        </select>
                    </div>
                </div>
                <div id="sharingSectionFormulir-${safeJenjang}" class="grid grid-cols-2 gap-4 p-4 bg-slate-50 dark:bg-gray-800 rounded-lg border border-slate-200 dark:border-gray-700" style="${penanggung !== 'sharing' ? 'display: none;' : ''}">
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">Kampus (%)</label>
                        <input type="number" class="formulir-persen-kampus w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${persenKampus}" min="0" max="100" step="0.1" oninput="updateFormulirPersen(this, '${escapeHtml(jenjang)}')">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">K2 (%)</label>
                        <input type="number" class="formulir-persen-k2 w-full px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm"
                            value="${persenK2}" min="0" max="100" step="0.1" oninput="updateFormulirPersen(this, '${escapeHtml(jenjang)}')">
                    </div>
                </div>
                <div id="previewFormulir-${safeJenjang}" class="p-3 bg-violet-50 dark:bg-violet-900/20 rounded-lg ${total > 0 ? '' : 'hidden'}">
                    <div class="text-xs font-medium text-violet-700 dark:text-violet-300 mb-2">Preview Bagi Hasil:</div>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div class="flex justify-between"><span>Kampus:</span><span class="font-semibold">Rp <span class="preview-kampus">${formatRupiah((total * persenKampus) / 100)}</span></span></div>
                        <div class="flex justify-between"><span>K2:</span><span class="font-semibold">Rp <span class="preview-k2">${formatRupiah((total * persenK2) / 100)}</span></span></div>
                    </div>
                </div>
            </div>
        `;

        container.appendChild(formulirItem);
        if (typeof lucide !== 'undefined') lucide.createIcons();
        updateBiayaFormulirData();
    }

    function toggleFormulirDetail(btn) {
        const item = btn.closest('.border');
        const detail = item.querySelector('.formulir-detail');
        const icon = btn.querySelector('i');
        if (detail.classList.contains('hidden')) {
            detail.classList.remove('hidden');
            icon.setAttribute('data-lucide', 'chevron-up');
        } else {
            detail.classList.add('hidden');
            icon.setAttribute('data-lucide', 'chevron-down');
        }
        if (typeof lucide !== 'undefined') lucide.createIcons();
    }

    function hapusBiayaFormulirItem(btn) {
        const item = btn.closest('#biayaFormulirContainer > div');
        const remainingItems = document.querySelectorAll('#biayaFormulirContainer > div');

        if (remainingItems.length <= 1) {
            Swal.fire({
                icon: 'warning',
                title: 'Peringatan',
                text: 'Minimal harus ada 1 jenjang formulir!',
                confirmButtonColor: '#f59e0b'
            });
            return;
        }

        const jenjang = item.dataset.jenjang;
        Swal.fire({
            title: 'Hapus Jenjang?',
            text: `Apakah Anda yakin ingin menghapus formulir untuk jenjang ${jenjang}?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Ya, Hapus',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#ef4444'
        }).then((result) => {
            if (result.isConfirmed) {
                item.remove();
                updateBiayaFormulirData();
            }
        });
    }

    function handleFormulirTotalInput(input) {
        let value = input.value.replace(/[^\d]/g, '');
        const actualInput = input.parentElement.querySelector('.formulir-total-actual');
        if (actualInput) actualInput.value = value || 0;
        input.value = value ? parseInt(value).toLocaleString('id-ID') : '';

        const item = input.closest('#biayaFormulirContainer > div');
        if (item) updateFormulirRupiahPreview(item);
        updateBiayaFormulirData();
    }

    function togglePenanggungFormulir(select, jenjang) {
        const safeJenjang = jenjang.replace(/[^a-zA-Z0-9]/g, '_');
        const sharingSection = document.getElementById(`sharingSectionFormulir-${safeJenjang}`);
        const persenKampusInput = document.querySelector(`#sharingSectionFormulir-${safeJenjang} .formulir-persen-kampus`);
        const persenK2Input = document.querySelector(`#sharingSectionFormulir-${safeJenjang} .formulir-persen-k2`);
        const item = document.querySelector(`#biayaFormulirContainer > div[data-jenjang="${jenjang}"]`);

        if (select.value === 'sharing') {
            // Default sharing: 70% kampus, 30% k2
            if (sharingSection) sharingSection.style.display = 'grid';
            if (persenKampusInput) {
                if (persenKampusInput.value == 0 || persenKampusInput.value == '' || persenKampusInput.value == 100) {
                    persenKampusInput.value = 70;
                }
                persenKampusInput.readOnly = false;
            }
            if (persenK2Input) {
                if (persenK2Input.value == 0 || persenK2Input.value == '' || persenK2Input.value == 100) {
                    persenK2Input.value = 30;
                }
                persenK2Input.readOnly = false;
            }
        } else {
            if (sharingSection) sharingSection.style.display = 'none';
            if (select.value === 'kampus') {
                if (persenKampusInput) { persenKampusInput.value = 100; persenKampusInput.readOnly = true; }
                if (persenK2Input) { persenK2Input.value = 0; persenK2Input.readOnly = true; }
            } else if (select.value === 'k2') {
                if (persenKampusInput) { persenKampusInput.value = 0; persenKampusInput.readOnly = true; }
                if (persenK2Input) { persenK2Input.value = 100; persenK2Input.readOnly = true; }
            }
        }

        if (item) updateFormulirRupiahPreview(item);
        updateBiayaFormulirData();
    }

    function updateFormulirPersen(input, jenjang) {
        const item = document.querySelector(`#biayaFormulirContainer > div[data-jenjang="${jenjang}"]`);
        if (!item) return;

        const persenKampusInput = item.querySelector('.formulir-persen-kampus');
        const persenK2Input = item.querySelector('.formulir-persen-k2');

        if (input.classList.contains('formulir-persen-kampus')) {
            const kampusVal = parseFloat(persenKampusInput?.value) || 0;
            if (persenK2Input) persenK2Input.value = 100 - kampusVal;
        } else if (input.classList.contains('formulir-persen-k2')) {
            const k2Val = parseFloat(persenK2Input?.value) || 0;
            if (persenKampusInput) persenKampusInput.value = 100 - k2Val;
        }

        updateFormulirRupiahPreview(item);
        updateBiayaFormulirData();
    }

    function updateFormulirRupiahPreview(item) {
        if (!item) return;

        const total = parseFloat(item.querySelector('.formulir-total-actual')?.value) || 0;
        const penanggung = item.querySelector('.formulir-penanggung')?.value || 'k2';
        let kampusPersen = 0, k2Persen = 0;

        if (penanggung === 'kampus') { kampusPersen = 100; k2Persen = 0; }
        else if (penanggung === 'k2') { kampusPersen = 0; k2Persen = 100; }
        else {
            kampusPersen = parseFloat(item.querySelector('.formulir-persen-kampus')?.value) || 0;
            k2Persen = parseFloat(item.querySelector('.formulir-persen-k2')?.value) || 0;
        }

        const previewKampus = item.querySelector('.preview-kampus');
        const previewK2 = item.querySelector('.preview-k2');
        if (previewKampus) previewKampus.textContent = formatRupiah((total * kampusPersen) / 100);
        if (previewK2) previewK2.textContent = formatRupiah((total * k2Persen) / 100);

        const jenjang = item.dataset.jenjang;
        const safeJenjang = jenjang.replace(/[^a-zA-Z0-9]/g, '_');
        const previewDiv = document.getElementById(`previewFormulir-${safeJenjang}`);
        if (previewDiv) {
            if (total > 0) previewDiv.classList.remove('hidden');
            else previewDiv.classList.add('hidden');
        }
    }

    function updateBiayaFormulirData() {
        const formulirData = {};
        document.querySelectorAll('#biayaFormulirContainer > div').forEach(item => {
            const jenjang = item.dataset.jenjang;
            if (jenjang) {
                const total = parseFloat(item.querySelector('.formulir-total-actual')?.value) || 0;
                const penanggung = item.querySelector('.formulir-penanggung')?.value || 'k2';
                let persenKampus = parseFloat(item.querySelector('.formulir-persen-kampus')?.value) || 0;
                let persenK2 = parseFloat(item.querySelector('.formulir-persen-k2')?.value) || 0;

                if (penanggung !== 'sharing') {
                    if (penanggung === 'kampus') { persenKampus = 100; persenK2 = 0; }
                    else { persenKampus = 0; persenK2 = 100; }
                } else {
                    // Jika sharing dan persen kosong, set default 70/30
                    if (persenKampus === 0 && persenK2 === 0) {
                        persenKampus = 70;
                        persenK2 = 30;
                    }
                }

                formulirData[jenjang] = {
                    total: total,
                    penanggung: penanggung,
                    persen_kampus: persenKampus,
                    persen_k2: persenK2
                };
            }
        });

        const formulirInput = document.getElementById('biayaFormulirInput');
        if (formulirInput) formulirInput.value = JSON.stringify(formulirData);
    }

    function formatRupiah(angka) {
        if (!angka || isNaN(angka)) return '0';
        return Math.round(angka).toLocaleString('id-ID');
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, m => m === '&' ? '&amp;' : m === '<' ? '&lt;' : '&gt;');
    }
</script>
<?php /**PATH C:\Users\User\Documents\K2-PROJECTS\k2-sipema\resources\views/rnd/kampus/partials/scripts.blade.php ENDPATH**/ ?>