// =========================================================================
// 📁 MODUL DATA SEKOLAH — PENERIMA MANFAAT (Siswa, Guru, Staf)
// =========================================================================

// State Variables
let dbSekolah = [];
let isSekolahLoaded = false;
let currentSekolahId = null;
let dbPenerima = [];
let isPenerimaLoaded = false;
let activeFilterJabatan = 'semua'; // 'semua', '1', '2', '3'
let jabatanList = ['Guru Kelas', 'Kepala Sekolah', 'Wakil Kepala Sekolah', 'Guru Olahraga', 'Guru Agama', 'Tenaga Administrasi', 'Petugas Kebersihan', 'Penjaga Sekolah', 'Pustakawan'];
let jabatanLoaded = false;

function escapeHTML(str) {
    if (str === null || str === undefined || str === '') return '';
    let div = document.createElement('div');
    div.appendChild(document.createTextNode(String(str)));
    return div.innerHTML;
}

function calculateAge(d) {
    if (!d || d === '-') return '-';
    let dob = new Date(d);
    let today = new Date();
    let age = today.getFullYear() - dob.getFullYear();
    let m = today.getMonth() - dob.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < dob.getDate())) {
        age--;
    }
    return age + ' Tahun';
}

function formatDateId(d) {
    if (!d || d === '-') return '-';
    let months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    let parts = d.split('-');
    if (parts.length === 3) {
        return parseInt(parts[2], 10) + ' ' + months[parseInt(parts[1], 10) - 1] + ' ' + parts[0];
    }
    return d;
}

/**
 * Format tanggal dari YYYY-MM-DD ke DD-MM-YYYY untuk tampilan
 */
function formatDateDMY(d) {
    if (!d || d === '-') return '-';
    let parts = d.split('-');
    if (parts.length === 3) {
        return parts[2] + '-' + parts[1] + '-' + parts[0];
    }
    return d;
}

function capitalizeWords(str) {
    if (!str) return '';
    return str.split(' ').map(function(w) {
        if (!w) return '';
        if (w.length >= 2 && w === w.toUpperCase() && /^[A-Z0-9]+$/.test(w)) return w;
        return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
    }).join(' ');
}

/**
 * Label jenis kelamin dari kode L/P
 */
function getJkLabel(jk) {
    if (jk === 'L') return 'Laki-Laki';
    if (jk === 'P') return 'Perempuan';
    return '-';
}

/**
 * Label posisi dari kode
 */
function getJabatanKodeLabel(kode) {
    if (kode === 1) return 'Siswa';
    if (kode === 2) return 'Guru / Kepsek';
    if (kode === 3) return 'Staf Lainnya';
    return '-';
}

// Helper dropdown wrapper
window.setDropdownValue = function(id, value) {
    let hiddenInput = document.getElementById(id);
    if (!hiddenInput) return;
    hiddenInput.value = value;
    let dropdown = hiddenInput.closest('.custom-dropdown');
    if (dropdown) {
        let item = dropdown.querySelector('.dropdown-item[data-value="' + escapeHTML(value).replace(/"/g, '&quot;') + '"]');
        if (item) {
            dropdown.querySelector('.dropdown-text').innerHTML = item.innerHTML;
        } else {
            dropdown.querySelector('.dropdown-text').innerHTML = escapeHTML(value);
        }
    }
};

window.renderDataSekolah = function(container) {
    container.innerHTML = `
    <div class="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
            <h2 class="text-2xl font-black text-gray-800 tracking-tight">Data Sekolah</h2>
            <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mt-1">Manajemen Sekolah & Madrasah</p>
        </div>
        <div class="flex gap-2">
            <button onclick="window.fetchSekolahData(false)" class="bg-white border-2 border-gray-100 hover:bg-gray-50 text-gray-600 px-4 py-2.5 rounded-xl font-bold text-xs uppercase tracking-widest shadow-sm transition-all"><i class="fa-solid fa-rotate-right mr-1"></i> Refresh</button>
            <button onclick="window.cetakSemuaSekolah()" class="bg-white border-2 border-gray-100 hover:bg-gray-50 text-gray-600 px-4 py-2.5 rounded-xl font-bold text-xs uppercase tracking-widest shadow-sm transition-all"><i class="fa-solid fa-print mr-1"></i> Cetak Semua</button>
            ${currentUser.role !== 'Operator Sasaran' ? `<button onclick="window.openModalSekolah()" class="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white px-5 py-2.5 rounded-xl shadow-lg shadow-blue-500/30 font-bold text-xs uppercase tracking-widest transition-all transform hover:-translate-y-0.5"><i class="fa-solid fa-plus mr-1"></i> Tambah Sekolah</button>` : ''}
        </div>
    </div>
    
    <div id="sekolahContainer" class="flex flex-col gap-5">
        <div class="text-center py-10"><i class="fa-solid fa-circle-notch fa-spin text-blue-500 text-3xl mb-3"></i><br><span class="text-gray-400 font-medium">Memuat data sekolah...</span></div>
    </div>
    `;

    setTimeout(() => {
        if(typeof flatpickr !== 'undefined') {
            flatpickr(".datepicker", { dateFormat: "Y-m-d" });
        }
    }, 500);

    fetchSekolahData(false);
};

window.fetchSekolahData = function(silent) {
    if (!silent) {
        let container = document.getElementById('sekolahContainer');
        if(container) container.innerHTML = '<div class="text-center py-10"><i class="fa-solid fa-circle-notch fa-spin text-blue-500 text-3xl mb-3"></i><br><span class="text-gray-400 font-medium">Memuat data sekolah...</span></div>';
    }
    
    axios.get('/api/data-sekolah', { params: { dapur_id: activeDapurContext } })
        .then(res => {
            if (res.data.success) {
                dbSekolah = res.data.data;
                isSekolahLoaded = true;
                if(document.getElementById('sekolahContainer')) renderSekolahList();
            } else {
                if(document.getElementById('sekolahContainer')) {
                    document.getElementById('sekolahContainer').innerHTML = `<div class="text-center py-10 text-red-500">${res.data.message || 'Gagal memuat data'}</div>`;
                }
            }
        })
        .catch(err => {
            if(document.getElementById('sekolahContainer')) {
                document.getElementById('sekolahContainer').innerHTML = '<div class="text-center py-10"><i class="fa-solid fa-triangle-exclamation text-red-400 text-4xl mb-3"></i><p class="text-gray-500">Error server/koneksi.</p></div>';
            }
        });
};

// Konfigurasi visual per jenjang
const _jenjangConfig = {
    'TK':  { label: 'TK / PAUD Sederajat', icon: 'fa-child-reaching', gradient: 'from-amber-500 to-orange-500', bg: 'bg-amber-50', border: 'border-amber-100', text: 'text-amber-600', shadow: 'shadow-amber-500/20', badge: 'bg-amber-100 text-amber-700 border-amber-200' },
    'SD':  { label: 'SD / MI Sederajat',    icon: 'fa-school',          gradient: 'from-blue-500 to-indigo-500',  bg: 'bg-blue-50',   border: 'border-blue-100',   text: 'text-blue-600',   shadow: 'shadow-blue-500/20',   badge: 'bg-blue-100 text-blue-700 border-blue-200' },
    'SMP': { label: 'SMP / MTs Sederajat',  icon: 'fa-building-columns', gradient: 'from-emerald-500 to-teal-500', bg: 'bg-emerald-50', border: 'border-emerald-100', text: 'text-emerald-600', shadow: 'shadow-emerald-500/20', badge: 'bg-emerald-100 text-emerald-700 border-emerald-200' },
    'SMA': { label: 'SMA / MA Sederajat',   icon: 'fa-graduation-cap', gradient: 'from-violet-500 to-purple-500', bg: 'bg-violet-50',  border: 'border-violet-100',  text: 'text-violet-600',  shadow: 'shadow-violet-500/20',  badge: 'bg-violet-100 text-violet-700 border-violet-200' },
};
const _jenjangOrderList = ['TK', 'SD', 'SMP', 'SMA'];

function renderSekolahList() {
    let container = document.getElementById('sekolahContainer');
    if (!container) return;
    
    if (dbSekolah.length === 0) {
        let emptyAddBtn = currentUser.role !== 'Operator Sasaran' ? '<button onclick="window.openModalSekolah()" class="bg-blue-100 text-blue-600 hover:bg-blue-200 px-4 py-2 rounded-lg text-sm font-semibold transition-colors mt-4">Tambah Sekarang</button>' : '';
        container.innerHTML = '<div class="bg-white border border-dashed border-gray-300 rounded-[2rem] p-16 flex flex-col items-center text-center"><i class="fa-solid fa-school-flag text-5xl text-gray-300 mb-4"></i><h5 class="text-lg font-bold text-gray-600">Belum ada Data Sekolah</h5>' + emptyAddBtn + '</div>';
        return;
    }

    let grouped = {};
    dbSekolah.forEach(item => {
        let j = (item.jenjang || 'SD').toUpperCase();
        if (!_jenjangConfig[j]) j = 'SD';
        if (!grouped[j]) grouped[j] = [];
        grouped[j].push(item);
    });

    const _naturalSort = (a, b) => {
        let na = a.nama_sekolah || '', nb = b.nama_sekolah || '';
        let numA = na.match(/\d+/), numB = nb.match(/\d+/);
        if (numA && numB) {
            let prefA = na.substring(0, numA.index).trim().toLowerCase();
            let prefB = nb.substring(0, numB.index).trim().toLowerCase();
            if (prefA !== prefB) return prefA.localeCompare(prefB);
            let diff = parseInt(numA[0], 10) - parseInt(numB[0], 10);
            if (diff !== 0) return diff;
            let suffA = na.substring(numA.index + numA[0].length).trim().toLowerCase();
            let suffB = nb.substring(numB.index + numB[0].length).trim().toLowerCase();
            return suffA.localeCompare(suffB);
        }
        if (numA && !numB) return 1;
        if (!numA && numB) return -1;
        return na.localeCompare(nb);
    };
    Object.keys(grouped).forEach(j => { grouped[j].sort(_naturalSort); });

    // Summary cards
    let summaryHtml = '<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-2">';
    _jenjangOrderList.forEach(j => {
        let cfg = _jenjangConfig[j];
        let count = (grouped[j] || []).length;
        let aktif = (grouped[j] || []).filter(s => s.status === 'Aktif').length;
        summaryHtml += `
            <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center gap-4 transition-all hover:shadow-md hover:-translate-y-0.5 cursor-default">
                <div class="w-12 h-12 shrink-0 rounded-xl bg-gradient-to-br ${cfg.gradient} flex items-center justify-center shadow-lg ${cfg.shadow}">
                    <i class="fa-solid ${cfg.icon} text-white text-lg"></i>
                </div>
                <div class="min-w-0">
                    <p class="text-2xl font-black text-gray-800 leading-none">${count}</p>
                    <p class="text-[10px] font-bold text-gray-400 uppercase tracking-widest mt-0.5">${j} Sederajat</p>
                    <p class="text-[10px] font-semibold ${cfg.text}">${aktif} aktif</p>
                </div>
            </div>`;
    });
    summaryHtml += '</div>';

    // Grouped sections
    let sectionsHtml = '';
    _jenjangOrderList.forEach(j => {
        let items = grouped[j];
        if (!items || items.length === 0) return;
        let cfg = _jenjangConfig[j];

        sectionsHtml += `
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 cursor-pointer select-none hover:bg-gray-50/50 transition-colors" onclick="window._toggleSekolahGroup('${j}')">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-gradient-to-br ${cfg.gradient} flex items-center justify-center shadow-md ${cfg.shadow}">
                        <i class="fa-solid ${cfg.icon} text-white text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-black text-gray-800 tracking-tight">${cfg.label}</h3>
                        <p class="text-[10px] font-bold text-gray-400 uppercase tracking-widest">${items.length} Sekolah Terdaftar</p>
                    </div>
                </div>
                <i id="sekolahGroupIcon-${j}" class="fa-solid fa-chevron-down text-gray-300 text-xs transition-transform duration-300"></i>
            </div>
            <div id="sekolahGroup-${j}" class="divide-y divide-gray-50">`;

        items.forEach((item, idx) => {
            let statusBadge = item.status === 'Aktif' 
                ? '<span class="bg-emerald-50 text-emerald-600 border border-emerald-100 text-[10px] font-bold px-2 py-0.5 rounded-md uppercase tracking-wider whitespace-nowrap">Aktif</span>' 
                : '<span class="bg-red-50 text-red-500 border border-red-100 text-[10px] font-bold px-2 py-0.5 rounded-md uppercase tracking-wider whitespace-nowrap">Nonaktif</span>';

            let actionBtns = currentUser.role !== 'Operator Sasaran' ? `
                <button onclick="event.stopPropagation(); window.openModalSekolah(${item.id})" class="w-8 h-8 rounded-lg bg-gray-50 hover:bg-blue-50 text-gray-300 hover:text-blue-600 flex items-center justify-center transition-all" title="Edit"><i class="fa-solid fa-pen text-xs"></i></button>
                <button onclick="event.stopPropagation(); window.deleteSekolah(${item.id})" class="w-8 h-8 rounded-lg bg-gray-50 hover:bg-red-50 text-gray-300 hover:text-red-500 flex items-center justify-center transition-all" title="Hapus"><i class="fa-solid fa-trash text-xs"></i></button>` : '';

            let dapurBadge = window.getDapurBadge ? window.getDapurBadge(item.dapur_id) : '';
            let totalPenerima = (item.siswa_count || 0) + (item.tendik_count || 0);

            sectionsHtml += `
                <div onclick="window.masukDetailSekolah(${item.id}, '${escapeHTML(item.nama_sekolah).replace(/'/g, "\\'")}', '${escapeHTML(item.alamat).replace(/'/g, "\\'")}')" 
                     class="flex items-center gap-4 px-5 py-3.5 hover:bg-gray-50/80 cursor-pointer transition-colors group">
                    <div class="w-7 h-7 shrink-0 rounded-lg ${cfg.bg} ${cfg.border} border flex items-center justify-center">
                        <span class="text-[11px] font-black ${cfg.text}">${idx + 1}</span>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-0.5">
                            <h5 class="text-sm font-bold text-gray-800 truncate" title="${escapeHTML(item.nama_sekolah)}">${escapeHTML(item.nama_sekolah)}</h5>
                            ${dapurBadge}
                        </div>
                        <p class="text-xs text-gray-400 truncate"><i class="fa-solid fa-location-dot mr-1 text-[10px]"></i>${escapeHTML(item.alamat || '-')}</p>
                        <div class="flex items-center gap-2 mt-1">
                            <span class="text-[10px] font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded-md border border-blue-100"><i class="fa-solid fa-user-graduate mr-1"></i>${item.siswa_count || 0} Siswa</span>
                            <span class="text-[10px] font-bold text-amber-600 bg-amber-50 px-2 py-0.5 rounded-md border border-amber-100"><i class="fa-solid fa-chalkboard-user mr-1"></i>${item.tendik_count || 0} Tendik</span>
                            <span class="text-[10px] font-bold text-gray-500 bg-gray-100 px-2 py-0.5 rounded-md border border-gray-200"><i class="fa-solid fa-users mr-1"></i>${totalPenerima} Total</span>
                        </div>
                    </div>
                    <div class="shrink-0 hidden sm:block">${statusBadge}</div>
                    <div class="shrink-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">${actionBtns}</div>
                    <i class="fa-solid fa-chevron-right text-[10px] text-gray-200 group-hover:text-blue-400 transition-colors shrink-0"></i>
                </div>`;
        });

        sectionsHtml += `</div></div>`;
    });

    container.innerHTML = summaryHtml + sectionsHtml;
}

window._toggleSekolahGroup = function(jenjang) {
    let group = document.getElementById('sekolahGroup-' + jenjang);
    let icon = document.getElementById('sekolahGroupIcon-' + jenjang);
    if (!group) return;
    if (group.classList.contains('hidden')) {
        group.classList.remove('hidden');
        if (icon) icon.classList.remove('rotate-180');
    } else {
        group.classList.add('hidden');
        if (icon) icon.classList.add('rotate-180');
    }
}

window.openModalSekolah = function(id) {
    if(!window.checkSuperAdminDapur('mengelola data sekolah')) return;
    if(document.getElementById('sekolahForm')) document.getElementById('sekolahForm').reset();
    
    if (id) {
        let item = dbSekolah.find(x => x.id == id);
        if (!item) return;
        document.getElementById('sekolahModalTitle').innerHTML = 'Edit Sekolah';
        document.getElementById('sekolah_id').value = item.id;
        document.getElementById('sekolah_nama').value = item.nama_sekolah;
        document.getElementById('sekolah_alamat').value = item.alamat;
        window.setDropdownValue('sekolah_status', item.status);
        window.setDropdownValue('sekolah_jenjang', item.jenjang || 'SD');
    } else {
        document.getElementById('sekolahModalTitle').innerHTML = 'Tambah Sekolah';
        document.getElementById('sekolah_id').value = '';
        window.setDropdownValue('sekolah_status', 'Aktif');
        window.setDropdownValue('sekolah_jenjang', 'SD');
    }
    
    let modal = document.getElementById('sekolahModal');
    if(modal) {
        modal.classList.remove('hidden');
        setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('div').classList.remove('scale-95'); }, 10);
    }
};

window.handleSekolahSubmit = function() {
    let payload = {
        id: document.getElementById('sekolah_id').value,
        nama_sekolah: capitalizeWords(document.getElementById('sekolah_nama').value.trim()),
        alamat: capitalizeWords(document.getElementById('sekolah_alamat').value.trim()),
        status: document.getElementById('sekolah_status').value,
        jenjang: document.getElementById('sekolah_jenjang').value
    };
    
    if (!payload.nama_sekolah) return ModernSwal.fire('Error', 'Nama sekolah wajib diisi', 'warning');
    
    window.startLoading('Menyimpan data...');
    axios.post('/api/data-sekolah', payload)
        .then(res => {
            window.endLoading();
            if(res.data.success) {
                ToastBg.fire({icon: 'success', title: 'Data Sekolah Disimpan'});
                window.closeSekolahModal();
                fetchSekolahData(true);
            } else {
                ModernSwal.fire('Gagal', res.data.message, 'error');
            }
        })
        .catch(err => {
            window.endLoading();
            ModernSwal.fire('Error', err.response?.data?.message || 'Terjadi kesalahan sistem', 'error');
        });
};

window.deleteSekolah = function(id) {
    if(!window.checkSuperAdminDapur('menghapus data sekolah')) return;
    ModernSwal.fire({
        title: 'Hapus Sekolah?',
        text: "Semua data penerima manfaat terkait akan terhapus permanen.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        confirmButtonText: 'Ya, Hapus',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            window.startLoading('Menghapus data...');
            axios.delete(`/api/data-sekolah/${id}`)
                .then(res => {
                    window.endLoading();
                    if(res.data.success) {
                        ToastBg.fire({icon: 'success', title: 'Sekolah Terhapus'});
                        fetchSekolahData(true);
                    } else {
                        ModernSwal.fire('Gagal', res.data.message, 'error');
                    }
                })
                .catch(err => {
                    window.endLoading();
                    ModernSwal.fire('Error', err.response?.data?.message || 'Terjadi kesalahan', 'error');
                });
        }
    });
};

window.closeSekolahModal = function() {
    let modal = document.getElementById('sekolahModal');
    if(!modal) return;
    modal.classList.add('opacity-0');
    modal.querySelector('div').classList.add('scale-95');
    setTimeout(() => { modal.classList.add('hidden'); }, 300);
};

// ==========================================
// DETAIL SEKOLAH — PENERIMA MANFAAT UNIFIED
// ==========================================
window.masukDetailSekolah = function(id, nama, alamat) {
    currentSekolahId = id;
    activeFilterJabatan = 'semua';
    
    let currSekolah = dbSekolah.find(x => x.id == id);
    let isTK = currSekolah && currSekolah.jenjang === 'TK';
    
    let container = document.getElementById('contentArea');
    
    container.innerHTML = `
    <div class="mb-6">
        <button onclick="window.switchMenu('datasekolah')" class="text-gray-400 hover:text-blue-600 font-bold text-sm mb-4 inline-flex items-center transition-colors"><i class="fa-solid fa-arrow-left mr-2"></i> Kembali ke Daftar Sekolah</button>
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <div class="w-14 h-14 bg-gradient-to-br from-blue-500 to-indigo-600 text-white rounded-2xl flex items-center justify-center shadow-lg shadow-blue-500/30">
                    <i class="fa-solid fa-school-flag text-2xl"></i>
                </div>
                <div>
                    <h2 class="text-2xl font-black text-gray-800 tracking-tight leading-none mb-1">${escapeHTML(nama)}</h2>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest"><i class="fa-solid fa-location-dot mr-1"></i> ${escapeHTML(alamat)}</p>
                </div>
            </div>
            <div class="flex items-center gap-2 flex-wrap">
                <button onclick="window.cetakPerSekolah()" class="bg-white border border-gray-200 text-gray-600 hover:bg-gray-50 px-4 py-2.5 rounded-xl shadow-sm transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-print"></i> Cetak</button>
                ${currentUser.role !== 'Operator Sasaran' ? `
                <button id="btnTambahPenerima" onclick="window.openPenerimaModal()" class="bg-gradient-to-r from-blue-600 to-blue-500 text-white px-4 py-2.5 rounded-xl shadow-lg shadow-blue-500/25 transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-plus"></i> Tambah Penerima</button>
                <button onclick="window.openImportPenerimaModal()" class="bg-white border border-emerald-200 text-emerald-600 hover:bg-emerald-50 px-4 py-2.5 rounded-xl shadow-sm transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-file-import"></i> Import</button>
                <button onclick="window.exportPenerimaManfaat()" class="bg-white border border-amber-200 text-amber-600 hover:bg-amber-50 px-4 py-2.5 rounded-xl shadow-sm transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-file-export"></i> Export</button>
                ${!isTK ? `<button onclick="window.promoteSiswaMassal()" class="bg-white border border-indigo-200 text-indigo-600 hover:bg-indigo-50 px-4 py-2.5 rounded-xl shadow-sm transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-arrow-up-right-dots"></i> Naik Kelas</button>` : ''}
                <button onclick="window.hapusSemuaPenerima()" class="bg-white border border-red-200 text-red-500 hover:bg-red-50 px-4 py-2.5 rounded-xl shadow-sm transition-all font-bold text-xs flex items-center gap-2 hover:-translate-y-0.5"><i class="fa-solid fa-trash-can"></i> Hapus Semua</button>
                ` : ''}
            </div>
        </div>
    </div>

    <!-- Summary Area -->
    <div id="penerimaGlobalSummary" class="mb-6"></div>
    
    <!-- Filter Posisi -->
    <div class="flex gap-2 mb-4 flex-wrap">
        <button onclick="window.filterJabatan('semua')" id="filterBtn-semua" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition-all border-2" style="background:#2563eb; color:#fff; border-color:#2563eb;"><i class="fa-solid fa-users mr-1.5"></i> Semua</button>
        <button onclick="window.filterJabatan('1')" id="filterBtn-1" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition-all border-2" style="background:#fff; color:#4b5563; border-color:#e5e7eb;"><i class="fa-solid fa-user-graduate mr-1.5"></i> Siswa</button>
        <button onclick="window.filterJabatan('2')" id="filterBtn-2" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition-all border-2" style="background:#fff; color:#4b5563; border-color:#e5e7eb;"><i class="fa-solid fa-chalkboard-user mr-1.5"></i> Guru & Kepsek</button>
        <button onclick="window.filterJabatan('3')" id="filterBtn-3" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition-all border-2" style="background:#fff; color:#4b5563; border-color:#e5e7eb;"><i class="fa-solid fa-user-tie mr-1.5"></i> Staf Lainnya</button>
    </div>
    
    <!-- Tabel Unified Penerima Manfaat -->
    <div class="bg-white border border-gray-100 rounded-2xl overflow-hidden shadow-[0_2px_15px_rgb(0,0,0,0.02)]">
        <div class="overflow-x-auto custom-scrollbar">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50/80 text-[10px] font-black text-gray-400 uppercase tracking-widest border-b border-gray-100">
                    <tr>
                        <th class="px-4 py-4 whitespace-nowrap">NISN</th>
                        <th class="px-4 py-4 whitespace-nowrap">Nama Penerima Manfaat</th>
                        <th class="px-4 py-4 whitespace-nowrap">Tgl Lahir</th>
                        <th class="px-4 py-4 text-center">Jenis Kelamin</th>
                        <th class="px-4 py-4 whitespace-nowrap">Nama Orang Tua</th>
                        <th class="px-4 py-4">Posisi</th>
                        ${!isTK ? '<th class="px-4 py-4">Kelas</th>' : ''}
                        <th class="px-4 py-4 whitespace-nowrap">Fisik</th>
                        <th class="px-4 py-4">Alergi</th>
                        <th class="px-4 py-4 text-center">Status</th>
                        <th class="px-4 py-4 text-right">Aksi</th>
                    </tr>
                </thead>
                <tbody id="tabelPenerimaBody" class="text-sm divide-y divide-gray-50">
                    <tr><td colspan="${!isTK ? 11 : 10}" class="px-6 py-10 text-center"><i class="fa-solid fa-circle-notch fa-spin text-blue-500 text-2xl mb-2"></i><br><span class="text-gray-400">Memuat data...</span></td></tr>
                </tbody>
            </table>
        </div>
    </div>
    `;
    
    // Fetch data
    window.startLoading('Memuat Detail...');
    axios.get(`/api/data-sekolah/${id}/detail`)
        .then(res => {
            window.endLoading();
            if(res.data.success) {
                dbPenerima = res.data.data;
                isPenerimaLoaded = true;
                renderPenerima();
                renderPenerimaSummary();
            }
        })
        .catch(err => {
            window.endLoading();
            ModernSwal.fire('Error', 'Gagal mengambil detail sekolah', 'error');
        });
};

window.filterJabatan = function(filter) {
    activeFilterJabatan = filter;
    
    // Update button styles
    ['semua', '1', '2', '3'].forEach(f => {
        let btn = document.getElementById('filterBtn-' + f);
        if (!btn) return;
        if (f === filter) {
            btn.style.background = '#2563eb';
            btn.style.color = '#fff';
            btn.style.borderColor = '#2563eb';
        } else {
            btn.style.background = '#fff';
            btn.style.color = '#4b5563';
            btn.style.borderColor = '#e5e7eb';
        }
    });
    
    renderPenerima();
};

function renderPenerimaSummary() {
    let container = document.getElementById('penerimaGlobalSummary');
    if (!container) return;
    
    let aktifData = dbPenerima.filter(p => p.status === 'Aktif');
    let totalSiswa = aktifData.filter(p => p.jabatan_kode === 1).length;
    let totalGuru = aktifData.filter(p => p.jabatan_kode === 2).length;
    let totalStaf = aktifData.filter(p => p.jabatan_kode === 3).length;
    let totalL = aktifData.filter(p => p.jenis_kelamin === 'L').length;
    let totalP = aktifData.filter(p => p.jenis_kelamin === 'P').length;
    
    let cardTemplate = (title, total, icon, colorClass, gradClass, shadowClass) => {
        return `<div class="bg-white rounded-2xl p-3 border border-gray-100 shadow-sm text-center break-inside-avoid">
            <div class="w-8 h-8 mx-auto mb-1 rounded-lg flex items-center justify-center bg-gradient-to-br ${gradClass} ${shadowClass} shadow-md">
                <i class="fa-solid ${icon} text-white text-sm"></i>
            </div>
            <p class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">${title}</p>
            <p class="text-2xl font-black text-gray-800 leading-tight">${total}</p>
            <p class="text-[9px] font-bold text-gray-400 uppercase">Orang</p>
        </div>`;
    };
    
    container.innerHTML = `<div class="grid grid-cols-2 md:grid-cols-5 gap-3">
        ${cardTemplate('Total Penerima', aktifData.length, 'fa-users', 'text-blue-500', 'from-blue-500 to-indigo-500', 'shadow-blue-500/30')}
        ${cardTemplate('Siswa', totalSiswa, 'fa-user-graduate', 'text-emerald-500', 'from-emerald-500 to-teal-500', 'shadow-emerald-500/30')}
        ${cardTemplate('Guru / Kepsek', totalGuru, 'fa-chalkboard-user', 'text-amber-500', 'from-amber-500 to-orange-500', 'shadow-amber-500/30')}
        ${cardTemplate('Staf Lainnya', totalStaf, 'fa-user-tie', 'text-violet-500', 'from-violet-500 to-purple-500', 'shadow-violet-500/30')}
        <div class="bg-white rounded-2xl p-3 border border-gray-100 shadow-sm text-center break-inside-avoid">
            <div class="w-8 h-8 mx-auto mb-1 rounded-lg flex items-center justify-center bg-gray-50"><i class="fa-solid fa-venus-mars text-gray-400 text-sm"></i></div>
            <p class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Gender</p>
            <div class="flex justify-center gap-2 mt-1">
                <span class="flex items-center gap-1 text-blue-600 bg-blue-50 border border-blue-200 px-2 py-0.5 rounded-md font-bold text-[10px]"><i class="fa-solid fa-mars text-[8px]"></i>${totalL}</span>
                <span class="flex items-center gap-1 text-pink-600 bg-pink-50 border border-pink-200 px-2 py-0.5 rounded-md font-bold text-[10px]"><i class="fa-solid fa-venus text-[8px]"></i>${totalP}</span>
            </div>
        </div>
    </div>`;
}

function renderPenerima() {
    let tbody = document.getElementById('tabelPenerimaBody');
    if (!tbody) return;
    
    let currSekolah = dbSekolah.find(x => x.id == currentSekolahId);
    let isTK = currSekolah && currSekolah.jenjang === 'TK';
    
    let filtered = dbPenerima;
    if (activeFilterJabatan !== 'semua') {
        filtered = dbPenerima.filter(p => p.jabatan_kode == activeFilterJabatan);
    }
    
    if (filtered.length === 0) {
        tbody.innerHTML = `<tr><td colspan="${!isTK ? 11 : 10}" class="px-6 py-10 text-center text-gray-400">Belum ada data penerima manfaat${activeFilterJabatan !== 'semua' ? ' untuk kategori ini' : ''}.</td></tr>`;
        return;
    }
    
    let html = '';
    filtered.forEach(item => {
        let isNonaktif = item.status === 'Nonaktif';
        let opacity = isNonaktif ? 'bg-gray-50/50 opacity-60' : 'hover:bg-gray-50/50 transition-colors';
        
        // Jabatan badge styling
        let jabatanBadge = '';
        if (item.jabatan_kode === 1) {
            jabatanBadge = `<span class="bg-blue-50 text-blue-600 border border-blue-100 text-[10px] font-bold px-2 py-0.5 rounded-md">${escapeHTML(item.jabatan || 'Siswa')}</span>`;
        } else if (item.jabatan_kode === 2) {
            jabatanBadge = `<span class="bg-amber-50 text-amber-600 border border-amber-100 text-[10px] font-bold px-2 py-0.5 rounded-md">${escapeHTML(item.jabatan || 'Guru')}</span>`;
        } else {
            jabatanBadge = `<span class="bg-violet-50 text-violet-600 border border-violet-100 text-[10px] font-bold px-2 py-0.5 rounded-md">${escapeHTML(item.jabatan || 'Staf')}</span>`;
        }
        
        let statusLabel = isNonaktif 
            ? '<span class="text-[10px] font-black uppercase text-red-500 bg-red-50 px-2 py-1 rounded">Tidak Aktif</span>' 
            : '<span class="text-[10px] font-black uppercase text-emerald-500 bg-emerald-50 px-2 py-1 rounded">Aktif</span>';
        
        let jkLabel = getJkLabel(item.jenis_kelamin);
        let jkStyle = item.jenis_kelamin === 'L' ? 'bg-blue-50 text-blue-600' : 'bg-pink-50 text-pink-600';
        
        // Actions
        let actionBtns = '';
        if (item.jabatan_kode === 1) {
            actionBtns += `<button onclick="window.openAntropometriModal('siswa', ${item.id}, '${escapeHTML(item.nama_penerima).replace(/'/g, "\\'")}')" class="text-emerald-500 hover:text-emerald-700 bg-emerald-50 w-8 h-8 rounded-lg mr-1" title="Pertumbuhan"><i class="fa-solid fa-chart-line text-xs"></i></button>`;
        }
        if (currentUser.role !== 'Operator Sasaran') {
            actionBtns += `<button onclick="window.openPenerimaModal(${item.id})" class="text-blue-500 hover:text-blue-700 bg-blue-50 w-8 h-8 rounded-lg mr-1"><i class="fa-solid fa-pen text-xs"></i></button>
            <button onclick="window.deletePenerima(${item.id})" class="text-red-500 hover:text-red-700 bg-red-50 w-8 h-8 rounded-lg"><i class="fa-solid fa-trash text-xs"></i></button>`;
        }
        
        html += `<tr class="${opacity}">
            <td class="px-4 py-4 font-medium text-gray-800 text-xs">${escapeHTML(item.nisn || '-')}</td>
            <td class="px-4 py-4 font-bold text-gray-800">${escapeHTML(item.nama_penerima)}</td>
            <td class="px-4 py-4 text-xs text-gray-600">${formatDateDMY(item.tanggal_lahir)}<br><span class="text-[10px] text-gray-400">${calculateAge(item.tanggal_lahir)}</span></td>
            <td class="px-4 py-4 text-center"><span class="${jkStyle} px-2 py-0.5 rounded text-[10px] font-bold">${jkLabel}</span></td>
            <td class="px-4 py-4 text-xs text-gray-600">${escapeHTML(item.nama_orangtua || '-')}</td>
            <td class="px-4 py-4">${jabatanBadge}</td>
            ${!isTK ? `<td class="px-4 py-4"><span class="bg-gray-100 border border-gray-200 text-gray-600 px-2.5 py-1 rounded-md text-xs font-bold">${escapeHTML(item.kelas || '-')}</span></td>` : ''}
            <td class="px-4 py-4 text-xs text-gray-500">${item.jabatan_kode === 1 ? `${escapeHTML(item.tinggi_badan)} cm<br>${escapeHTML(item.berat_badan)} kg` : '-'}</td>
            <td class="px-4 py-4 text-xs text-gray-500 max-w-[100px] truncate" title="${escapeHTML(item.alergi)}">${escapeHTML(item.alergi || '-')}</td>
            <td class="px-4 py-4 text-center">${statusLabel}</td>
            <td class="px-4 py-4 text-right whitespace-nowrap">${actionBtns}</td>
        </tr>`;
    });
    tbody.innerHTML = html;
}

// ==========================================
// MODAL: TAMBAH/EDIT PENERIMA MANFAAT
// ==========================================

// === JABATAN MANAGEMENT (per-Dapur) ===
function loadJabatanList() {
    if (jabatanLoaded) return Promise.resolve();
    return axios.get('/api/dapur-settings')
        .then(res => {
            if (res.data.success && res.data.settings && res.data.settings.jabatan_list) {
                jabatanList = res.data.settings.jabatan_list;
            }
            jabatanLoaded = true;
        })
        .catch(() => { jabatanLoaded = true; });
}

function saveJabatanList() {
    return axios.post('/api/dapur-settings', { key: 'jabatan_list', value: jabatanList })
        .catch(() => {});
}

function renderJabatanDropdown(selectedValue) {
    let menu = document.getElementById('penerimaJabatanMenu');
    if (!menu) return;
    let html = '';
    jabatanList.forEach(jab => {
        let isSelected = jab === selectedValue;
        html += `<div class="px-5 py-3 hover:bg-amber-50 cursor-pointer text-sm font-bold text-gray-700 transition-colors dropdown-item ${isSelected ? 'bg-amber-50 text-amber-600' : ''}" data-value="${escapeHTML(jab)}">
            ${escapeHTML(jab)}
        </div>`;
    });
    html += `<div class="px-5 py-3 hover:bg-emerald-50 cursor-pointer text-sm font-bold text-emerald-600 transition-colors border-t border-gray-100 flex items-center gap-2" onclick="window.tambahJabatanBaru()">
        <i class="fas fa-plus-circle"></i> Tambah Posisi Baru
    </div>`;
    menu.innerHTML = html;
}

window.tambahJabatanBaru = function() {
    let dd = document.querySelector('#penerimaJabatanMenu')?.closest('.custom-dropdown');
    if (dd) {
        let ddMenu = dd.querySelector('.dropdown-menu');
        if (ddMenu) { ddMenu.classList.add('opacity-0', 'invisible', 'translate-y-2'); ddMenu.classList.remove('opacity-100', 'visible', 'translate-y-0'); }
        let icon = dd.querySelector('.dropdown-icon');
        if (icon) icon.style.transform = '';
    }

    ModernSwal.fire({
        title: 'Tambah Posisi Baru',
        input: 'text',
        inputPlaceholder: 'Contoh: Guru Olahraga',
        inputAttributes: { style: 'text-transform: capitalize;' },
        showCancelButton: true,
        confirmButtonText: 'Tambah',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#f59e0b',
        inputValidator: (value) => {
            if (!value || !value.trim()) return 'Nama posisi tidak boleh kosong';
            if (jabatanList.includes(value.trim())) return 'Posisi sudah ada';
        }
    }).then(result => {
        if (result.isConfirmed && result.value) {
            let newJab = result.value.trim().split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
            jabatanList.push(newJab);
            saveJabatanList();
            window.setDropdownValue('penerima_jabatan', newJab);
            renderJabatanDropdown(newJab);
            ToastBg.fire({ icon: 'success', title: `Posisi "${newJab}" ditambahkan` });
        }
    });
};

window.openPenerimaModal = function(id) {
    if(!window.checkSuperAdminDapur('mengelola data penerima manfaat')) return;
    if(document.getElementById('penerimaForm')) document.getElementById('penerimaForm').reset();
    let fp = document.getElementById('penerima_tgl')._flatpickr; if (fp) fp.clear();
    
    let currSekolah = dbSekolah.find(x => x.id == currentSekolahId);
    let isTK = currSekolah && currSekolah.jenjang === 'TK';
    
    // Show/hide jabatan-dependent fields
    function updateJabatanFields(jabatanKode) {
        let kelasContainer = document.getElementById('penerima_kelas_container');
        let fisikContainer = document.getElementById('penerima_fisik_container');
        let noHpContainer = document.getElementById('penerima_nohp_container');
        let jabatanDetailContainer = document.getElementById('penerima_jabatan_detail_container');
        
        if (jabatanKode == 1) {
            // Siswa: show kelas & fisik, hide no_hp, hide jabatan detail
            if (kelasContainer) kelasContainer.style.display = isTK ? 'none' : 'block';
            if (fisikContainer) fisikContainer.style.display = 'block';
            if (noHpContainer) noHpContainer.style.display = 'none';
            if (jabatanDetailContainer) jabatanDetailContainer.style.display = 'none';
        } else {
            // Guru/Staf: hide kelas & fisik, show no_hp & jabatan detail
            if (kelasContainer) kelasContainer.style.display = 'none';
            if (fisikContainer) fisikContainer.style.display = 'none';
            if (noHpContainer) noHpContainer.style.display = 'block';
            if (jabatanDetailContainer) jabatanDetailContainer.style.display = 'block';
        }
    }
    
    // Store callback on window for jabatan_kode change
    window._onJabatanKodeChange = updateJabatanFields;
    
    loadJabatanList().then(() => {
        if (id) {
            let item = dbPenerima.find(x => x.id == id);
            if (!item) return;
            document.getElementById('penerimaModalTitle').innerHTML = 'Edit Penerima Manfaat';
            document.getElementById('penerima_id').value = item.id;
            document.getElementById('penerima_nisn').value = item.nisn || '';
            document.getElementById('penerima_nama').value = item.nama_penerima;
            document.getElementById('penerima_nama_orangtua').value = item.nama_orangtua || '';
            document.getElementById('penerima_kelas').value = item.kelas || '';
            document.getElementById('penerima_tb').value = item.tinggi_badan || 0;
            document.getElementById('penerima_bb').value = item.berat_badan || 0;
            document.getElementById('penerima_alergi').value = item.alergi || '-';
            document.getElementById('penerima_hp').value = item.no_hp || '';
            if (fp) fp.setDate(item.tanggal_lahir); else document.getElementById('penerima_tgl').value = item.tanggal_lahir;
            window.setDropdownValue('penerima_jk', item.jenis_kelamin || 'L');
            window.setDropdownValue('penerima_status', item.status || 'Aktif');
            window.setDropdownValue('penerima_jabatan_kode', String(item.jabatan_kode || 1));
            
            let selectedJab = item.jabatan || 'Siswa';
            if (item.jabatan_kode !== 1 && !jabatanList.includes(selectedJab)) {
                jabatanList.push(selectedJab);
                saveJabatanList();
            }
            renderJabatanDropdown(selectedJab);
            window.setDropdownValue('penerima_jabatan', selectedJab);
            
            updateJabatanFields(item.jabatan_kode);
        } else {
            document.getElementById('penerimaModalTitle').innerHTML = 'Tambah Penerima Manfaat';
            document.getElementById('penerima_id').value = '';
            document.getElementById('penerima_alergi').value = '-';
            document.getElementById('penerima_tb').value = 0;
            document.getElementById('penerima_bb').value = 0;
            window.setDropdownValue('penerima_jk', 'L');
            window.setDropdownValue('penerima_status', 'Aktif');
            window.setDropdownValue('penerima_jabatan_kode', '1');
            renderJabatanDropdown('Guru Kelas');
            window.setDropdownValue('penerima_jabatan', 'Guru Kelas');
            
            updateJabatanFields(1);
        }
        
        let modal = document.getElementById('penerimaModal');
        if(modal) {
            modal.classList.remove('hidden');
            setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('div').classList.remove('scale-95'); }, 10);
        }
    });
};

window.handlePenerimaSubmit = function() {
    let currSekolah = dbSekolah.find(x => x.id == currentSekolahId);
    let isTK = currSekolah && currSekolah.jenjang === 'TK';
    let jabatanKode = parseInt(document.getElementById('penerima_jabatan_kode').value) || 1;
    
    let payload = {
        id: document.getElementById('penerima_id').value,
        id_sekolah: currentSekolahId,
        nisn: document.getElementById('penerima_nisn').value.trim().toUpperCase(),
        nama_penerima: capitalizeWords(document.getElementById('penerima_nama').value.trim()),
        jenis_kelamin: document.getElementById('penerima_jk').value,
        tanggal_lahir: document.getElementById('penerima_tgl').value,
        nama_orangtua: capitalizeWords(document.getElementById('penerima_nama_orangtua').value.trim()),
        jabatan_kode: jabatanKode,
        jabatan: jabatanKode === 1 ? 'Siswa' : document.getElementById('penerima_jabatan').value,
        kelas: jabatanKode === 1 ? (isTK ? '-' : document.getElementById('penerima_kelas').value.trim().toUpperCase()) : null,
        tinggi_badan: jabatanKode === 1 ? document.getElementById('penerima_tb').value : 0,
        berat_badan: jabatanKode === 1 ? document.getElementById('penerima_bb').value : 0,
        alergi: capitalizeWords(document.getElementById('penerima_alergi').value.trim()),
        no_hp: jabatanKode !== 1 ? document.getElementById('penerima_hp').value.trim() : null,
        status: document.getElementById('penerima_status').value
    };
    
    if(!payload.nama_penerima) return ModernSwal.fire('Peringatan', 'Nama Penerima Manfaat wajib diisi', 'warning');
    if(!payload.tanggal_lahir) return ModernSwal.fire('Peringatan', 'Tanggal Lahir wajib diisi', 'warning');
    
    window.startLoading('Menyimpan data...');
    axios.post('/api/data-siswa', payload)
        .then(res => {
            if(res.data.success) {
                ToastBg.fire({icon: 'success', title: 'Data Penerima Manfaat Disimpan'});
                window.closePenerimaModal();
                axios.get(`/api/data-sekolah/${currentSekolahId}/detail`).then(r => {
                    if(r.data.success) { dbPenerima = r.data.data; renderPenerima(); renderPenerimaSummary(); }
                    window.endLoading();
                });
            } else {
                window.endLoading();
                ModernSwal.fire('Gagal', res.data.message, 'error');
            }
        })
        .catch(err => {
            window.endLoading();
            ModernSwal.fire('Error', err.response?.data?.message || 'Terjadi kesalahan sistem', 'error');
        });
};

window.deletePenerima = function(id) {
    ModernSwal.fire({
        title: 'Hapus Penerima Manfaat?',
        text: "Data akan terhapus permanen.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        confirmButtonText: 'Ya, Hapus'
    }).then((result) => {
        if (result.isConfirmed) {
            window.startLoading('Menghapus...');
            axios.delete(`/api/data-siswa/${id}`)
                .then(res => {
                    if(res.data.success) {
                        ToastBg.fire({icon: 'success', title: 'Data Terhapus'});
                        dbPenerima = dbPenerima.filter(x => x.id != id);
                        renderPenerima();
                        renderPenerimaSummary();
                        window.endLoading();
                    }
                }).catch(() => window.endLoading());
        }
    });
};

window.closePenerimaModal = function() {
    let modal = document.getElementById('penerimaModal');
    if(!modal) return;
    modal.classList.add('opacity-0');
    modal.querySelector('div').classList.add('scale-95');
    setTimeout(() => { modal.classList.add('hidden'); }, 300);
};

// ==========================================
// MASS ACTIONS (Import & Promote)
// ==========================================
window.openImportPenerimaModal = function() {
    document.getElementById('import_penerima_data').value = '';
    // Reset file input
    let fileInput = document.getElementById('import_penerima_file');
    if (fileInput) fileInput.value = '';
    let label = document.getElementById('fileUploadLabel');
    if (label) label.innerHTML = '<i class="fa-solid fa-cloud-arrow-up text-4xl text-gray-300 mb-3"></i><p class="text-sm font-bold text-gray-500">Klik atau drag file Excel di sini</p><p class="text-xs text-gray-400 mt-1">Format: .xlsx atau .xls</p>';
    window._importFileData = null;
    window.switchImportTab('paste');
    let modal = document.getElementById('importPenerimaModal');
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); }, 10);
};
window.closeImportPenerimaModal = function() {
    let modal = document.getElementById('importPenerimaModal');
    modal.classList.add('opacity-0');
    setTimeout(() => { modal.classList.add('hidden'); }, 300);
};

// Tab switching for import
window._importMode = 'paste';
window.switchImportTab = function(mode) {
    window._importMode = mode;
    let tabPaste = document.getElementById('tabPaste');
    let tabFile = document.getElementById('tabFile');
    let panelPaste = document.getElementById('panelPaste');
    let panelFile = document.getElementById('panelFile');
    
    if (mode === 'paste') {
        tabPaste.style.background = '#2563eb';
        tabPaste.style.color = '#fff';
        tabPaste.style.borderColor = '#2563eb';
        tabFile.style.background = '#fff';
        tabFile.style.color = '#4b5563';
        tabFile.style.borderColor = '#e5e7eb';
        panelPaste.style.display = '';
        panelFile.style.display = 'none';
    } else {
        tabFile.style.background = '#2563eb';
        tabFile.style.color = '#fff';
        tabFile.style.borderColor = '#2563eb';
        tabPaste.style.background = '#fff';
        tabPaste.style.color = '#4b5563';
        tabPaste.style.borderColor = '#e5e7eb';
        panelPaste.style.display = 'none';
        panelFile.style.display = '';
    }
};

// Handle file selection
window.onImportFileSelected = function(input) {
    if (!input.files || !input.files[0]) return;
    let file = input.files[0];
    let label = document.getElementById('fileUploadLabel');
    label.innerHTML = `<i class="fa-solid fa-file-excel text-4xl text-emerald-500 mb-3"></i><p class="text-sm font-bold text-emerald-600">${file.name}</p><p class="text-xs text-gray-400 mt-1">${(file.size / 1024).toFixed(1)} KB — Siap diimport</p>`;
    
    // Read file using FileReader
    let reader = new FileReader();
    reader.onload = function(e) {
        window._importFileData = e.target.result;
    };
    reader.readAsArrayBuffer(file);
};

// Parse Excel file to rows using SheetJS
function parseExcelToRows(data) {
    if (typeof XLSX === 'undefined') {
        ModernSwal.fire('Error', 'Library XLSX belum dimuat. Silakan gunakan mode Paste Data.', 'error');
        return null;
    }
    try {
        let workbook = XLSX.read(data, { type: 'array' });
        let sheet = workbook.Sheets[workbook.SheetNames[0]];
        let jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: '' });
        
        // Skip header rows (row 1 = column names, row 2 = descriptions), and skip empty rows
        let rows = [];
        let startRow = 2; // Skip first 2 rows (index 0 and 1)
        
        // Auto-detect: if row 2 looks like description (contains format hints), skip 2 rows
        // Otherwise skip only 1 row (for old-style templates)
        if (jsonData.length > 1) {
            let row2 = jsonData[1];
            let isDescRow = row2.some(c => {
                let s = String(c).toLowerCase();
                return s.includes('format') || s.includes('digit') || s.includes('contoh') || s.includes('isi:') || s.includes('dalam cm') || s.includes('dalam kg');
            });
            startRow = isDescRow ? 2 : 1;
        }
        
        for (let i = startRow; i < jsonData.length; i++) {
            let row = jsonData[i];
            // Check if row has at least a name (col index 1)
            if (row.length >= 2 && row[1] && String(row[1]).trim()) {
                rows.push(row.map(c => String(c).trim()));
            }
        }
        return rows;
    } catch (e) {
        ModernSwal.fire('Error', 'Gagal membaca file Excel: ' + e.message, 'error');
        return null;
    }
}

function parsePenerimaColumns(cols) {
    // Format: NISN/NIK | Nama | Tgl Lahir | JK (392/64) | Ortu | Posisi (1/2/3) | Status (true/false) | TB | BB | Kelas | Alergi | No HP
    
    // === Jenis Kelamin: 392=Laki-laki, 64=Perempuan ===
    let jkRaw = cols[3] ? String(cols[3]).trim() : '392';
    let jk, jkKode;
    if (jkRaw === '392') { jk = 'L'; jkKode = 392; }
    else if (jkRaw === '64') { jk = 'P'; jkKode = 64; }
    else if (jkRaw.toUpperCase() === 'L' || jkRaw.toLowerCase().includes('laki')) { jk = 'L'; jkKode = 392; }
    else if (jkRaw.toUpperCase() === 'P' || jkRaw.toLowerCase().includes('perempuan')) { jk = 'P'; jkKode = 64; }
    else { jk = 'L'; jkKode = 392; }
    
    // === Posisi: 1=Siswa, 2=Guru/Kepala Sekolah, 3=Staf Lainnya ===
    let jabatanRaw = cols[5] ? String(cols[5]).trim() : '1';
    let jabatanKode, jabatan;
    if (jabatanRaw === '1') { jabatanKode = 1; jabatan = 'Siswa'; }
    else if (jabatanRaw === '2') { jabatanKode = 2; jabatan = 'Guru'; }
    else if (jabatanRaw === '3') { jabatanKode = 3; jabatan = 'Staf'; }
    else {
        jabatan = capitalizeWords(jabatanRaw);
        let jLower = jabatanRaw.toLowerCase();
        if (jLower === 'siswa' || jLower === 'pelajar') jabatanKode = 1;
        else if (jLower.includes('guru') || jLower.includes('kepala sekolah') || jLower.includes('kepsek')) jabatanKode = 2;
        else jabatanKode = 3;
    }
    
    // === Status: true=Aktif, false=Nonaktif ===
    let statusRaw = cols[6] ? String(cols[6]).trim().toLowerCase() : 'true';
    let status = (statusRaw === 'true' || statusRaw === '1' || statusRaw === 'aktif' || statusRaw === 'active') ? 'Aktif' : 'Nonaktif';
    let statusKode = status === 'Aktif';
    
    return {
        nisn: cols[0] ? String(cols[0]).trim() : '',
        nama_penerima: capitalizeWords(String(cols[1]).trim()),
        tanggal_lahir: cols[2] ? String(cols[2]).trim() : '',
        jenis_kelamin: jk,
        jenis_kelamin_kode: jkKode,
        nama_orangtua: cols[4] ? capitalizeWords(String(cols[4]).trim()) : '',
        jabatan_kode: jabatanKode,
        jabatan: jabatan,
        status: status,
        status_kode: statusKode,
        tinggi_badan: cols[7] ? parseFloat(String(cols[7]).replace(',','.')) || 0 : 0,
        berat_badan: cols[8] ? parseFloat(String(cols[8]).replace(',','.')) || 0 : 0,
        kelas: cols[9] ? String(cols[9]).trim().toUpperCase() : '',
        alergi: cols[10] ? capitalizeWords(String(cols[10]).trim()) : '-',
        no_hp: cols[11] ? String(cols[11]).trim() : '',
    };
}

window.handleImportPenerimaSubmit = function() {
    let parsedData = [];
    
    if (window._importMode === 'file') {
        // File upload mode
        if (!window._importFileData) {
            return ModernSwal.fire('Error', 'Belum ada file yang dipilih', 'warning');
        }
        let rows = parseExcelToRows(window._importFileData);
        if (!rows) return;
        
        rows.forEach(cols => {
            if (cols.length >= 2) {
                parsedData.push(parsePenerimaColumns(cols));
            }
        });
    } else {
        // Paste mode
        let text = document.getElementById('import_penerima_data').value.trim();
        if (!text) return ModernSwal.fire('Error', 'Data paste kosong', 'warning');
        
        let rows = text.split('\n');
        rows.forEach(r => {
            let cols = r.split('\t');
            if (cols.length >= 2) {
                parsedData.push(parsePenerimaColumns(cols));
            }
        });
    }
    
    if (parsedData.length === 0) return ModernSwal.fire('Error', 'Tidak ada data valid ditemukan', 'warning');
    
    window.startLoading('Mengimpor data penerima manfaat...');
    axios.post('/api/data-siswa/import', { id_sekolah: currentSekolahId, data: parsedData })
        .then(res => {
            window.endLoading();
            if(res.data.success) {
                ModernSwal.fire('Sukses', `${res.data.count} Data berhasil diimpor`, 'success');
                window.closeImportPenerimaModal();
                window.masukDetailSekolah(currentSekolahId, document.querySelector('h2').innerText, '');
            } else {
                ModernSwal.fire('Gagal', res.data.message, 'error');
            }
        }).catch(err => {
            window.endLoading();
            ModernSwal.fire('Error', 'Gagal memproses import', 'error');
        });
};

window.promoteSiswaMassal = function() {
    ModernSwal.fire({
        title: 'Proses Naik Kelas?',
        html: "Semua siswa <b>Aktif</b> akan dinaikkan kelasnya (contoh: 1A jadi 2A). Siswa kelas 6/9/12 akan di-set menjadi <b>Nonaktif</b> (Lulus).",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#4f46e5',
        confirmButtonText: 'Ya, Proses Sekarang'
    }).then((result) => {
        if (result.isConfirmed) {
            window.startLoading('Memproses...');
            axios.post(`/api/data-siswa/promote/${currentSekolahId}`)
                .then(res => {
                    window.endLoading();
                    if (res.data.success) {
                        ModernSwal.fire('Sukses', `${res.data.count} siswa telah diperbarui`, 'success');
                        window.masukDetailSekolah(currentSekolahId, document.querySelector('h2').innerText, '');
                    }
                }).catch(() => {
                    window.endLoading();
                    ModernSwal.fire('Error', 'Gagal memproses naik kelas', 'error');
                });
        }
    });
};

window.hapusSemuaPenerima = function() {
    ModernSwal.fire({
        title: 'Hapus Semua Penerima Manfaat?',
        text: 'Apakah Anda yakin ingin menghapus seluruh data penerima manfaat (siswa, guru, staf) di sekolah ini secara permanen?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#94a3b8',
        confirmButtonText: 'Ya, Hapus Semua!'
    }).then((result) => {
        if (result.isConfirmed) {
            ModernSwal.fire({ title: 'Menghapus...', html: '<i class="fas fa-spinner fa-spin text-4xl text-blue-500 mb-3 mt-2"></i>', showConfirmButton: false, allowOutsideClick: false });
            axios.delete(`/api/data-siswa/truncate/${currentSekolahId}`)
                .then(res => {
                    if (res.data.success) {
                        ModernSwal.fire('Terhapus!', res.data.message, 'success');
                        dbPenerima = [];
                        renderPenerima();
                        renderPenerimaSummary();
                    } else { ModernSwal.fire('Gagal', res.data.message, 'error'); }
                })
                .catch(err => { ModernSwal.fire('Error', err.response?.data?.message || err.message, 'error'); });
        }
    });
};

// =========================================================
// 📊 FUNGSI ANTROPOMETRI (RIWAYAT PERTUMBUHAN)
// =========================================================
window._antroChartInstance = null;

window.openAntropometriModal = function(entityType, entityId, namaDisplay) {
    document.getElementById('antro_entity_type').value = entityType;
    document.getElementById('antro_entity_id').value = entityId;

    let titleEl = document.getElementById('antropometriModalTitle');
    let subtitleEl = document.getElementById('antropometriModalSubtitle');
    if(titleEl) titleEl.innerHTML = 'Riwayat Pertumbuhan';
    if(subtitleEl) subtitleEl.innerHTML = namaDisplay || 'Data';

    let tglEl = document.getElementById('antro_tgl');
    if(tglEl) {
        if(tglEl._flatpickr) tglEl._flatpickr.setDate(new Date());
        else tglEl.value = new Date().toISOString().split('T')[0];
    }
    let tbEl = document.getElementById('antro_tb'); if(tbEl) tbEl.value = '';
    let bbEl = document.getElementById('antro_bb'); if(bbEl) bbEl.value = '';

    let modal = document.getElementById('antropometriModal');
    if(modal) {
        modal.classList.remove('hidden');
        setTimeout(() => {
            modal.classList.remove('opacity-0');
            modal.querySelector('div').classList.remove('scale-95');
        }, 10);
    }

    if(tglEl && typeof flatpickr !== 'undefined' && !tglEl._flatpickr) {
        flatpickr(tglEl, { dateFormat: 'Y-m-d', defaultDate: new Date() });
    }

    window.fetchAntropometriData(entityType, entityId);
};

window.closeAntropometriModal = function() {
    let modal = document.getElementById('antropometriModal');
    if(modal) {
        modal.classList.add('opacity-0');
        modal.querySelector('div').classList.add('scale-95');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }
    if(window._antroChartInstance) {
        window._antroChartInstance.destroy();
        window._antroChartInstance = null;
    }
};

window.fetchAntropometriData = function(entityType, entityId) {
    let tbody = document.getElementById('antropometriTableBody');
    if(tbody) tbody.innerHTML = '<tr><td colspan="4" class="text-center p-6 text-gray-400 text-xs"><i class="fas fa-spinner fa-spin mr-2"></i>Memuat data...</td></tr>';

    axios.get(`/api/antropometri/${entityType}/${entityId}`)
        .then(res => {
            if(res.data.success) {
                window.renderAntropometriTable(res.data.data);
                window.renderAntropometriChart(res.data.data);
            }
        })
        .catch(err => {
            if(tbody) tbody.innerHTML = '<tr><td colspan="4" class="text-center p-6 text-red-400 text-xs"><i class="fas fa-exclamation-triangle mr-2"></i>Gagal memuat data</td></tr>';
        });
};

window.renderAntropometriTable = function(data) {
    let tbody = document.getElementById('antropometriTableBody');
    if(!tbody) return;
    if(!data || data.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center p-6 text-gray-400 text-xs"><i class="fas fa-inbox text-2xl mb-2 block"></i>Belum ada data pengukuran</td></tr>';
        return;
    }
    let html = '';
    let sorted = [...data].sort((a, b) => new Date(b.tanggal_ukur) - new Date(a.tanggal_ukur));
    sorted.forEach((row, idx) => {
        let tgl = new Date(row.tanggal_ukur);
        let tglStr = tgl.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });
        let isLatest = idx === 0;
        html += `<tr class="${isLatest ? 'bg-emerald-50/50' : 'hover:bg-gray-50'} transition">
                <td class="p-3 text-xs font-semibold ${isLatest ? 'text-emerald-700' : 'text-gray-600'}">${isLatest ? '<i class="fas fa-star text-amber-400 mr-1"></i>' : ''}${tglStr}</td>
                <td class="p-3 text-xs font-bold ${isLatest ? 'text-emerald-700' : 'text-gray-700'}">${parseFloat(row.tinggi_badan).toFixed(1)} cm</td>
                <td class="p-3 text-xs font-bold ${isLatest ? 'text-emerald-700' : 'text-gray-700'}">${parseFloat(row.berat_badan).toFixed(1)} kg</td>
                <td class="p-3 text-right"><button onclick="window.deleteAntropometri(${row.id})" class="text-red-400 hover:text-red-600 bg-red-50 hover:bg-red-100 w-7 h-7 rounded-lg transition" title="Hapus"><i class="fas fa-trash-alt text-[10px]"></i></button></td>
            </tr>`;
    });
    tbody.innerHTML = html;
};

window.renderAntropometriChart = function(data) {
    let canvas = document.getElementById('personalGrowthChart');
    if(!canvas) return;
    if(window._antroChartInstance) { window._antroChartInstance.destroy(); window._antroChartInstance = null; }
    if(!data || data.length === 0) {
        let ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.font = '13px Inter, sans-serif'; ctx.fillStyle = '#9ca3af'; ctx.textAlign = 'center';
        ctx.fillText('Belum ada data pengukuran', canvas.width / 2, canvas.height / 2);
        return;
    }
    let sorted = [...data].sort((a, b) => new Date(a.tanggal_ukur) - new Date(b.tanggal_ukur));
    let labels = sorted.map(d => new Date(d.tanggal_ukur).toLocaleDateString('id-ID', { day: '2-digit', month: 'short' }));
    let tbData = sorted.map(d => parseFloat(d.tinggi_badan));
    let bbData = sorted.map(d => parseFloat(d.berat_badan));
    window._antroChartInstance = new Chart(canvas, {
        type: 'line',
        data: { labels, datasets: [
            { label: 'Tinggi Badan (cm)', data: tbData, borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', borderWidth: 2.5, pointBackgroundColor: '#10b981', pointBorderColor: '#fff', pointBorderWidth: 2, pointRadius: 5, pointHoverRadius: 7, tension: 0.3, fill: true, yAxisID: 'yTB' },
            { label: 'Berat Badan (kg)', data: bbData, borderColor: '#6366f1', backgroundColor: 'rgba(99,102,241,0.1)', borderWidth: 2.5, pointBackgroundColor: '#6366f1', pointBorderColor: '#fff', pointBorderWidth: 2, pointRadius: 5, pointHoverRadius: 7, tension: 0.3, fill: true, yAxisID: 'yBB' }
        ]},
        options: { responsive: true, maintainAspectRatio: false, interaction: { intersect: false, mode: 'index' },
            plugins: { legend: { position: 'top', labels: { usePointStyle: true, pointStyle: 'circle', padding: 15, font: { size: 11, weight: 'bold' } } }, tooltip: { backgroundColor: 'rgba(15,23,42,0.9)', titleFont: { weight: 'bold', size: 12 }, bodyFont: { size: 11 }, padding: 12, cornerRadius: 10 } },
            scales: { x: { grid: { display: false }, ticks: { font: { size: 10, weight: '600' }, color: '#94a3b8' } },
                yTB: { type: 'linear', position: 'left', title: { display: true, text: 'TB (cm)', font: { size: 10, weight: 'bold' }, color: '#10b981' }, grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { font: { size: 10 }, color: '#10b981' } },
                yBB: { type: 'linear', position: 'right', title: { display: true, text: 'BB (kg)', font: { size: 10, weight: 'bold' }, color: '#6366f1' }, grid: { drawOnChartArea: false }, ticks: { font: { size: 10 }, color: '#6366f1' } }
            }
        }
    });
};

window.saveAntropometri = function() {
    let entityType = document.getElementById('antro_entity_type').value;
    let entityId = document.getElementById('antro_entity_id').value;
    let tglEl = document.getElementById('antro_tgl');
    let tanggalUkur = tglEl._flatpickr ? tglEl._flatpickr.selectedDates[0] : tglEl.value;
    if(tanggalUkur instanceof Date) tanggalUkur = tanggalUkur.toISOString().split('T')[0];
    let tb = document.getElementById('antro_tb').value;
    let bb = document.getElementById('antro_bb').value;
    if(!tb || !bb || (!parseFloat(tb) && !parseFloat(bb))) return ModernSwal.fire('Perhatian', 'Tinggi Badan dan Berat Badan harus diisi', 'warning');
    window.startLoading('Menyimpan pengukuran...');
    axios.post('/api/antropometri', { entity_type: entityType, entity_id: entityId, tinggi_badan: parseFloat(tb), berat_badan: parseFloat(bb), tanggal_ukur: tanggalUkur })
    .then(res => { window.endLoading(); if(res.data.success) { ToastBg.fire({ icon: 'success', title: 'Data pengukuran tersimpan!' }); document.getElementById('antro_tb').value = ''; document.getElementById('antro_bb').value = ''; window.fetchAntropometriData(entityType, entityId); } else { ModernSwal.fire('Gagal', res.data.message || 'Gagal menyimpan', 'error'); } })
    .catch(err => { window.endLoading(); ModernSwal.fire('Error', err.response?.data?.message || 'Terjadi kesalahan', 'error'); });
};

window.deleteAntropometri = function(id) {
    let entityType = document.getElementById('antro_entity_type').value;
    let entityId = document.getElementById('antro_entity_id').value;
    ModernSwal.fire({ title: 'Hapus Pengukuran?', text: 'Data pengukuran ini akan dihapus permanen.', icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444', confirmButtonText: 'Ya, Hapus' }).then(result => {
        if(result.isConfirmed) { window.startLoading('Menghapus...'); axios.delete(`/api/antropometri/${id}`).then(res => { window.endLoading(); if(res.data.success) { ToastBg.fire({ icon: 'success', title: 'Data pengukuran dihapus' }); window.fetchAntropometriData(entityType, entityId); } }).catch(() => { window.endLoading(); ModernSwal.fire('Error', 'Gagal menghapus data', 'error'); }); }
    });
};

window.uploadTemplate = function(type, input) {
    if (!input.files || input.files.length === 0) return;
    let file = input.files[0];
    let allowedExt = ['xlsx', 'xls'];
    let ext = file.name.split('.').pop().toLowerCase();
    if (!allowedExt.includes(ext)) { ModernSwal.fire('Format Salah', 'Harap upload file Microsoft Excel (.xlsx atau .xls)', 'error'); input.value = ''; return; }
    if (file.size > 5 * 1024 * 1024) { ModernSwal.fire('File Kebesaran', 'Ukuran file maksimal 5MB', 'error'); input.value = ''; return; }
    let formData = new FormData(); formData.append('file', file);
    ModernSwal.fire({ title: 'Mengunggah Template...', html: 'Mohon tunggu sebentar', allowOutsideClick: false, didOpen: () => { ModernSwal.showLoading() } });
    axios.post(`/api/template/${type}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { if (res.data.success) { ModernSwal.fire('Berhasil!', res.data.message || 'Template berhasil diunggah.', 'success'); } else { ModernSwal.fire('Gagal', res.data.message || 'Gagal mengunggah template.', 'error'); } }).catch(err => { ModernSwal.fire('Error', 'Terjadi kesalahan saat mengunggah.', 'error'); }).finally(() => { input.value = ''; });
};

// ==========================================
// CETAK / PRINT FUNCTIONS
// ==========================================
function _printStyles() {
    return `<style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        body { font-family: 'Inter', sans-serif; font-size: 11px; color: #1f2937; padding: 30px 40px; }
        @page { margin: 10mm 15mm 15mm 15mm; size: A4 portrait; }
        @media print { body { padding: 0; } .school-block { page-break-inside: avoid; } .no-print { display: none !important; } }
        .doc-title { font-size: 16px; font-weight: 800; text-align: center; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 2px; }
        .doc-subtitle { text-align: center; font-size: 11px; color: #475569; margin-bottom: 18px; font-weight: 600; }
        .school-block { margin-bottom: 28px; page-break-inside: avoid; }
        .school-header { font-size: 13px; font-weight: 700; background: linear-gradient(135deg, #eff6ff, #f0f9ff); padding: 10px 14px; border-radius: 6px; margin-bottom: 10px; border-left: 4px solid #2563eb; color: #1e3a5f; }
        .school-header .sch-addr { font-weight: 400; color: #64748b; font-size: 10px; margin-top: 2px; }
        .section-title { font-size: 11px; font-weight: 700; color: #1e293b; margin: 14px 0 6px; padding: 4px 10px; background: #f8fafc; border-left: 3px solid #3b82f6; border-radius: 3px; text-transform: uppercase; letter-spacing: 0.8px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 14px; font-size: 10px; border: 1px solid #cbd5e1; }
        thead th { background: #1e293b; color: #fff; text-align: left; padding: 7px 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; font-size: 9px; border: 1px solid #334155; }
        tbody td { padding: 6px 10px; border: 1px solid #e2e8f0; }
        tbody tr:nth-child(even) td { background: #f8fafc; }
        .td-center { text-align: center; }
        .empty-msg { color: #94a3b8; font-style: italic; padding: 12px; text-align: center; border: 1px dashed #cbd5e1; border-radius: 6px; margin-bottom: 14px; }
        .print-footer { text-align: right; font-size: 9px; color: #94a3b8; margin-top: 15px; border-top: 1px dashed #cbd5e1; padding-top: 6px; }
    </style>`;
}

function _openPrintWindow(title, bodyHtml) {
    let w = window.open('', '_blank');
    w.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${_printStyles()}</head><body>${bodyHtml}<div class="print-footer">Dicetak pada ${new Date().toLocaleDateString('id-ID', {weekday:'long', day:'numeric', month:'long', year:'numeric'})} pukul ${new Date().toLocaleTimeString('id-ID')}</div></body></html>`);
    w.document.close();
    w.onload = function() { w.print(); };
}

function _getKopHeader() {
    let dapurId = activeDapurContext;
    let dapurName = dapurId === 'ALL' ? "SEMUA CABANG DAPUR" : (globalDapurList.find(d => d.ID_Dapur === dapurId)?.Nama_Dapur || dapurId).toUpperCase();
    return window.generateGlobalPrintHeader(dapurId, dapurName);
}

function _renderPenerimaTable(dataList) {
    if (!dataList || dataList.length === 0) return '<div class="empty-msg">Tidak ada data penerima manfaat terdaftar.</div>';
    let html = `<table><thead><tr><th style="width:30px" class="td-center">No</th><th style="width:85px">NISN</th><th>Nama Penerima</th><th style="width:30px" class="td-center">L/P</th><th style="width:85px">Tgl Lahir</th><th style="width:90px">Nama Ortu</th><th style="width:90px">Jabatan</th><th style="width:40px" class="td-center">Kelas</th><th>Alergi</th></tr></thead><tbody>`;
    dataList.forEach((s, i) => {
        let jkLabel = s.jenis_kelamin === 'L' ? 'Laki-Laki' : (s.jenis_kelamin === 'P' ? 'Perempuan' : '-');
        let jabLabel = s.jabatan || (s.jabatan_kode === 1 ? 'Siswa' : (s.jabatan_kode === 2 ? 'Guru/Kepsek' : 'Staf'));
        html += `<tr><td class="td-center">${i+1}</td><td>${s.nisn||'-'}</td><td><b>${s.nama_penerima}</b></td><td class="td-center">${jkLabel}</td><td>${formatDateDMY(s.tanggal_lahir)}</td><td>${s.nama_orangtua||'-'}</td><td>${jabLabel}</td><td class="td-center">${s.kelas||'-'}</td><td>${s.alergi||'-'}</td></tr>`;
    });
    return html + '</tbody></table>';
}

window.cetakSemuaSekolah = function() {
    ModernSwal.fire({ title: 'Menyiapkan data cetak...', html: '<i class="fas fa-spinner fa-spin text-4xl text-blue-500 mb-3 mt-2"></i>', showConfirmButton: false, allowOutsideClick: false });
    axios.get('/api/data-sekolah/print-all')
        .then(res => {
            ModernSwal.close();
            if (!res.data.success || !res.data.data.length) return ModernSwal.fire('Info', 'Tidak ada data sekolah aktif.', 'info');
            let bodyHtml = _getKopHeader();
            bodyHtml += '<div class="doc-title">Rekap Data Sekolah</div>';
            bodyHtml += '<div class="doc-subtitle">Seluruh Data Penerima Manfaat</div>';
            res.data.data.forEach((sekolah, index) => {
                let pbStyle = index > 0 ? ' style="page-break-before: always; padding-top: 10px;"' : '';
                bodyHtml += `<div class="school-block"${pbStyle}>
                    <div class="school-header">${sekolah.nama_sekolah}<div class="sch-addr">${sekolah.jenjang || ''} — ${sekolah.alamat || '-'}</div></div>
                    <div class="section-title">Data Penerima Manfaat (${sekolah.data.length} orang)</div>
                    ${_renderPenerimaTable(sekolah.data)}
                </div>`;
            });
            _openPrintWindow('Rekap Data Sekolah', bodyHtml);
        })
        .catch(() => { ModernSwal.fire('Error', 'Gagal memuat data cetak.', 'error'); });
};

window.cetakPerSekolah = function() {
    let sekolah = dbSekolah.find(x => x.id == currentSekolahId);
    let nama = sekolah ? sekolah.nama_sekolah : 'Sekolah';
    let alamat = sekolah ? sekolah.alamat : '';
    let activePenerima = dbPenerima.filter(p => p.status === 'Aktif');

    let bodyHtml = _getKopHeader();
    bodyHtml += `<div class="doc-title">${nama}</div>`;
    bodyHtml += `<div class="doc-subtitle">${alamat || '-'}</div>`;
    bodyHtml += `<div class="section-title">Data Penerima Manfaat Aktif (${activePenerima.length} orang)</div>`;
    bodyHtml += _renderPenerimaTable(activePenerima);

    _openPrintWindow('Data ' + nama, bodyHtml);
};

// ==========================================
// EXPORT PENERIMA MANFAAT (BGN / LAPORAN)
// ==========================================

window.exportPenerimaManfaat = function() {
    if (!dbPenerima || dbPenerima.length === 0) {
        return ModernSwal.fire('Info', 'Belum ada data penerima manfaat untuk diexport.', 'info');
    }

    let sekolah = dbSekolah.find(x => x.id == currentSekolahId);
    let namaSekolah = sekolah ? sekolah.nama_sekolah : 'Sekolah';

    ModernSwal.fire({
        title: '<i class="fa-solid fa-file-export text-amber-500"></i> Export Data',
        html: `
            <p style="color:#64748b;font-size:14px;margin-bottom:20px">Pilih format export untuk <strong>${escapeHTML(namaSekolah)}</strong></p>
            <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap">
                <button id="btnExportBGN" style="
                    background:linear-gradient(135deg,#1e40af,#3b82f6);color:#fff;
                    border:none;border-radius:16px;padding:20px 24px;cursor:pointer;
                    width:200px;text-align:center;transition:all 0.2s;box-shadow:0 4px 15px rgba(59,130,246,0.3)
                " onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='translateY(0)'">
                    <div style="font-size:28px;margin-bottom:8px"><i class="fa-solid fa-database"></i></div>
                    <div style="font-weight:800;font-size:14px;margin-bottom:4px">Export BGN</div>
                    <div style="font-size:10px;opacity:0.8;line-height:1.4">Format kode (392/64, 1/2/3, true/false)<br>7 kolom untuk sistem BGN</div>
                </button>
                <button id="btnExportLaporan" style="
                    background:linear-gradient(135deg,#065f46,#10b981);color:#fff;
                    border:none;border-radius:16px;padding:20px 24px;cursor:pointer;
                    width:200px;text-align:center;transition:all 0.2s;box-shadow:0 4px 15px rgba(16,185,129,0.3)
                " onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='translateY(0)'">
                    <div style="font-size:28px;margin-bottom:8px"><i class="fa-solid fa-file-lines"></i></div>
                    <div style="font-weight:800;font-size:14px;margin-bottom:4px">Export Laporan</div>
                    <div style="font-size:10px;opacity:0.8;line-height:1.4">Format lengkap & terbaca<br>Semua 12 kolom</div>
                </button>
            </div>
        `,
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: 'Batal',
        customClass: { popup: 'swal2-popup-lg' },
        didOpen: () => {
            document.getElementById('btnExportBGN').addEventListener('click', () => {
                ModernSwal.close();
                doExportPenerima('bgn', namaSekolah);
            });
            document.getElementById('btnExportLaporan').addEventListener('click', () => {
                ModernSwal.close();
                doExportPenerima('laporan', namaSekolah);
            });
        }
    });
};

function doExportPenerima(type, namaSekolah) {
    // Server-side export — PhpSpreadsheet generates styled .xlsx
    let url = `/api/data-siswa/export/${currentSekolahId}?type=${type}`;
    window.open(url, '_blank');
}
