<?php 
include 'koneksi.php';
cek_akses(['Super Admin', 'Kepala']);

$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'siswa';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Import Data Excel - Sistem Administrasi Guru</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        .content-wrapper {
            background: #f1f5f9;
        }
        .import-card {
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        .import-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 60px rgba(0,0,0,0.15);
        }
        .upload-area {
            border: 2px dashed #cbd5e1;
            border-radius: 16px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f8fafc;
        }
        .upload-area:hover {
            border-color: #1e3c72;
            background: #f1f5f9;
        }
        .upload-area.drag-over {
            border-color: #10b981;
            background: #f0fdf4;
        }
        .preview-table {
            max-height: 400px;
            overflow-y: auto;
            border-radius: 16px;
        }
        .nav-tabs-custom .nav-link {
            border-radius: 12px 12px 0 0;
            padding: 12px 24px;
            font-weight: 600;
            color: #64748b;
        }
        .nav-tabs-custom .nav-link.active {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            border: none;
        }
        .btn-gradient {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border: none;
            color: white;
        }
        .btn-gradient:hover {
            background: linear-gradient(135deg, #2a5298 0%, #1e3c72 100%);
            transform: translateY(-2px);
        }
        .table-responsive-custom {
            overflow-x: auto;
        }
        .info-box {
            background: #e8f0fe;
            border-left: 4px solid #1e3c72;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 font-weight-bold">
                            <i class="fas fa-file-excel text-success"></i> Import Data Excel
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Import Excel</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <!-- Tab Navigation -->
                <ul class="nav nav-tabs nav-tabs-custom mb-4" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link <?= $active_tab == 'siswa' ? 'active' : '' ?>" href="?tab=siswa">
                            <i class="fas fa-user-graduate"></i> Import Data Siswa
                        </a>
                    </li>
                    <?php if($_SESSION['role'] == 'Super Admin'): ?>
                    <li class="nav-item">
                        <a class="nav-link <?= $active_tab == 'user' ? 'active' : '' ?>" href="?tab=user">
                            <i class="fas fa-users"></i> Import Data User
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>

                <?php if($active_tab == 'siswa'): ?>
                <!-- ==================== IMPORT DATA SISWA ==================== -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="card import-card">
                            <div class="card-header bg-gradient-primary text-white">
                                <h4><i class="fas fa-user-graduate"></i> Import Data Siswa dari Excel</h4>
                            </div>
                            <div class="card-body">
                                <div class="info-box">
                                    <i class="fas fa-info-circle text-primary fa-2x float-left mr-3"></i>
                                    <div>
                                        <strong>Petunjuk:</strong>
                                        <ol class="mb-0 mt-2">
                                            <li>Download template Excel dengan klik tombol di bawah</li>
                                            <li>Isi data siswa sesuai format (NIS, Nama, Kelas, Unit, Status)</li>
                                            <li>NIS harus unik dan tidak boleh kosong</li>
                                            <li>Kelas akan otomatis dibuat jika belum ada</li>
                                            <li>Upload file Excel yang sudah diisi</li>
                                            <li>Preview data akan muncul, klik Import untuk menyimpan</li>
                                        </ol>
                                    </div>
                                </div>

                                <div class="alert alert-info">
                                    <i class="fas fa-table"></i> 
                                    <strong>Format File Excel yang Diperlukan:</strong>
                                    <hr class="my-2">
                                    <div class="table-responsive-custom">
                                        <table class="table table-sm table-bordered mt-2">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Kolom A</th>
                                                    <th>Kolom B</th>
                                                    <th>Kolom C</th>
                                                    <th>Kolom D</th>
                                                    <th>Kolom E</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td><strong>NIS</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Nama Siswa</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Kelas</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Unit</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Status</strong></td>
                                                </tr>
                                                <tr>
                                                    <td>2024001</td>
                                                    <td>Ahmad Budiman</td>
                                                    <td>Kelas 1A</td>
                                                    <td>Madrasah Ibtidaiyah</td>
                                                    <td>Aktif</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <button class="btn btn-sm btn-success mt-2" id="downloadTemplateSiswa">
                                        <i class="fas fa-download"></i> Download Template Excel
                                    </button>
                                </div>

                                <div id="siswaUploadArea" class="upload-area">
                                    <i class="fas fa-cloud-upload-alt fa-4x text-primary mb-3"></i>
                                    <h5>Drag & Drop file Excel di sini</h5>
                                    <p class="text-muted">atau</p>
                                    <button type="button" class="btn btn-primary" onclick="$('#siswaFileInput').click()">
                                        <i class="fas fa-folder-open"></i> Pilih File
                                    </button>
                                    <input type="file" id="siswaFileInput" accept=".xlsx,.xls" style="display: none;">
                                    <p class="mt-3 text-muted small">Maksimal ukuran file: 5MB</p>
                                </div>
                                
                                <div id="siswaFileName" class="text-center mt-3" style="display: none;">
                                    <i class="fas fa-file-excel text-success fa-2x"></i>
                                    <p><strong><span id="siswaFileNameText"></span></strong></p>
                                    <p class="text-muted">Jumlah data: <span id="siswaJumlahData">0</span> baris</p>
                                </div>

                                <div id="siswaPreviewSection" style="display: none; margin-top: 30px;">
                                    <h5><i class="fas fa-eye"></i> Preview Data Siswa</h5>
                                    <div class="preview-table mt-3">
                                        <table class="table table-bordered table-striped table-hover">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>No</th>
                                                    <th>NIS</th>
                                                    <th>Nama Siswa</th>
                                                    <th>Kelas</th>
                                                    <th>Unit</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody id="siswaPreviewBody"></tbody>
                                        </table>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <button class="btn btn-warning" onclick="resetSiswaImport()">
                                            <i class="fas fa-undo"></i> Upload Ulang
                                        </button>
                                        <button class="btn btn-success" onclick="importSiswaData()" id="btnImportSiswa">
                                            <i class="fas fa-database"></i> Import Data ke Database
                                        </button>
                                    </div>
                                </div>

                                <div id="siswaResultSection" style="display: none; margin-top: 30px;">
                                    <div id="siswaResultMessage"></div>
                                    <div class="text-center mt-3">
                                        <button class="btn btn-primary" onclick="resetSiswaImport()">
                                            <i class="fas fa-plus"></i> Import Lagi
                                        </button>
                                        <a href="kelola_siswa.php" class="btn btn-info">
                                            <i class="fas fa-list"></i> Lihat Data Siswa
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php else: ?>
                <!-- ==================== IMPORT DATA USER ==================== -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="card import-card">
                            <div class="card-header bg-gradient-primary text-white">
                                <h4><i class="fas fa-users"></i> Import Data User dari Excel</h4>
                            </div>
                            <div class="card-body">
                                <div class="info-box">
                                    <i class="fas fa-info-circle text-primary fa-2x float-left mr-3"></i>
                                    <div>
                                        <strong>Petunjuk Import User:</strong>
                                        <ol class="mb-0 mt-2">
                                            <li>Download template Excel di bawah</li>
                                            <li>Isi data user (Username, Password, Nama Lengkap, Role, Unit)</li>
                                            <li>Role yang tersedia: Super Admin, Pimpinan, Kepala, Guru</li>
                                            <li>Unit: MIJ, Kelompok Bermain, Raudhatul Athfal, Madrasah Ibtidaiyah, Madrasah Tsanawiyah, Madrasah Aliyah, Istiqlal Boarding School</li>
                                            <li>Username harus unik</li>
                                        </ol>
                                    </div>
                                </div>

                                <div class="alert alert-info">
                                    <i class="fas fa-table"></i> 
                                    <strong>Format File Excel yang Diperlukan:</strong>
                                    <hr class="my-2">
                                    <div class="table-responsive-custom">
                                        <table class="table table-sm table-bordered mt-2">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Kolom A</th>
                                                    <th>Kolom B</th>
                                                    <th>Kolom C</th>
                                                    <th>Kolom D</th>
                                                    <th>Kolom E</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td><strong>Username</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Password</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Nama Lengkap</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Role</strong> <span class="text-danger">*</span></td>
                                                    <td><strong>Unit</strong> <span class="text-danger">*</span></td>
                                                </tr>
                                                <tr>
                                                    <td>guru1</td>
                                                    <td>123456</td>
                                                    <td>Ahmad Guru</td>
                                                    <td>Guru</td>
                                                    <td>Madrasah Ibtidaiyah</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <small class="text-muted d-block mt-2">* Role: Super Admin, Pimpinan, Kepala, Guru</small>
                                    <small class="text-muted d-block">* Unit: MIJ, Kelompok Bermain, Raudhatul Athfal, Madrasah Ibtidaiyah, Madrasah Tsanawiyah, Madrasah Aliyah, Istiqlal Boarding School</small>
                                    <br>
                                    <button class="btn btn-sm btn-success mt-2" id="downloadTemplateUser">
                                        <i class="fas fa-download"></i> Download Template Excel
                                    </button>
                                </div>

                                <div id="userUploadArea" class="upload-area">
                                    <i class="fas fa-cloud-upload-alt fa-4x text-primary mb-3"></i>
                                    <h5>Drag & Drop file Excel di sini</h5>
                                    <p class="text-muted">atau</p>
                                    <button type="button" class="btn btn-primary" onclick="$('#userFileInput').click()">
                                        <i class="fas fa-folder-open"></i> Pilih File
                                    </button>
                                    <input type="file" id="userFileInput" accept=".xlsx,.xls" style="display: none;">
                                    <p class="mt-3 text-muted small">Maksimal ukuran file: 5MB</p>
                                </div>
                                
                                <div id="userFileName" class="text-center mt-3" style="display: none;">
                                    <i class="fas fa-file-excel text-success fa-2x"></i>
                                    <p><strong><span id="userFileNameText"></span></strong></p>
                                    <p class="text-muted">Jumlah data: <span id="userJumlahData">0</span> baris</p>
                                </div>

                                <div id="userPreviewSection" style="display: none; margin-top: 30px;">
                                    <h5><i class="fas fa-eye"></i> Preview Data User</h5>
                                    <div class="preview-table mt-3">
                                        <table class="table table-bordered table-striped table-hover">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>No</th>
                                                    <th>Username</th>
                                                    <th>Password</th>
                                                    <th>Nama Lengkap</th>
                                                    <th>Role</th>
                                                    <th>Unit</th>
                                                </tr>
                                            </thead>
                                            <tbody id="userPreviewBody"></tbody>
                                        </table>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <button class="btn btn-warning" onclick="resetUserImport()">
                                            <i class="fas fa-undo"></i> Upload Ulang
                                        </button>
                                        <button class="btn btn-success" onclick="importUserData()" id="btnImportUser">
                                            <i class="fas fa-database"></i> Import Data ke Database
                                        </button>
                                    </div>
                                </div>

                                <div id="userResultSection" style="display: none; margin-top: 30px;">
                                    <div id="userResultMessage"></div>
                                    <div class="text-center mt-3">
                                        <button class="btn btn-primary" onclick="resetUserImport()">
                                            <i class="fas fa-plus"></i> Import Lagi
                                        </button>
                                        <a href="kelola_user.php" class="btn btn-info">
                                            <i class="fas fa-list"></i> Lihat Data User
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> Madrasah Istiqlal - Sistem Administrasi Guru.</strong>
        All rights reserved.
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-0.20.2/package/dist/xlsx.full.min.js"></script>

<script>
// ==================== SISWA ====================
let siswaData = [];

const siswaUploadArea = document.getElementById('siswaUploadArea');
const siswaFileInput = document.getElementById('siswaFileInput');

if(siswaUploadArea) {
    siswaUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        siswaUploadArea.classList.add('drag-over');
    });
    
    siswaUploadArea.addEventListener('dragleave', () => {
        siswaUploadArea.classList.remove('drag-over');
    });
    
    siswaUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        siswaUploadArea.classList.remove('drag-over');
        const file = e.dataTransfer.files[0];
        if(file) handleSiswaFile(file);
    });
    
    siswaUploadArea.addEventListener('click', () => {
        siswaFileInput.click();
    });
}

if(siswaFileInput) {
    siswaFileInput.addEventListener('change', (e) => {
        if(e.target.files[0]) handleSiswaFile(e.target.files[0]);
    });
}

// Perbaiki fungsi handleSiswaFile
function handleSiswaFile(file) {
    if(!file.name.match(/\.(xlsx|xls)$/)) {
        alert('File harus berformat .xlsx atau .xls');
        return;
    }
    
    const reader = new FileReader();
    reader.onload = function(e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, {type: 'array'});
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        
        // Baca sebagai string untuk menjaga format NIS
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { 
            header: 1, 
            defval: "",
            raw: false  // Penting: jangan konversi ke number
        });
        
        // Skip header, ambil data dari baris 2
        siswaData = [];
        for(var i = 1; i < jsonData.length; i++) {
            var row = jsonData[i];
            // Pastikan NIS tidak kosong
            if(row[0] && row[0].toString().trim() !== '') {
                // Konversi NIS ke string untuk menjaga format
                var nis = row[0].toString().trim();
                // Jika NIS adalah number, tetap dipertahankan
                if(!isNaN(nis) && nis.includes('.')) {
                    nis = nis.split('.')[0];
                }
                siswaData.push([
                    nis,
                    row[1] ? row[1].toString().trim() : '',
                    row[2] ? row[2].toString().trim() : '',
                    row[3] ? row[3].toString().trim() : '',
                    row[4] ? row[4].toString().trim() : 'Aktif'
                ]);
            }
        }
        
        if(siswaData.length === 0) {
            alert('File Excel kosong atau tidak ada data!');
            return;
        }
        
        document.getElementById('siswaFileNameText').innerHTML = file.name;
        document.getElementById('siswaJumlahData').innerHTML = siswaData.length;
        document.getElementById('siswaFileName').style.display = 'block';
        
        previewSiswaData();
        document.getElementById('siswaPreviewSection').style.display = 'block';
        document.getElementById('siswaUploadArea').style.display = 'none';
    };
    reader.readAsArrayBuffer(file);
}

function previewSiswaData() {
    const tbody = document.getElementById('siswaPreviewBody');
    tbody.innerHTML = '';
    
    siswaData.slice(0, 10).forEach((row, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${index + 1}</td>
            <td><span class="badge bg-secondary">${escapeHtml(row[0])}</span></td>
            <td><strong>${escapeHtml(row[1])}</strong></td>
            <td>${escapeHtml(row[2])}</td>
            <td>${escapeHtml(row[3])}</td>
            <td>${escapeHtml(row[4])}</td>
        `;
        tbody.appendChild(tr);
    });
    
    if(siswaData.length > 10) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="6" class="text-center text-muted">... dan ${siswaData.length - 10} data lainnya</td>`;
        tbody.appendChild(tr);
    }
}

function escapeHtml(str) {
    if(!str) return '';
    return str.toString().replace(/[&<>]/g, function(m) {
        if(m === '&') return '&amp;';
        if(m === '<') return '&lt;';
        if(m === '>') return '&gt;';
        return m;
    });
}

function resetSiswaImport() {
    location.reload();
}

function importSiswaData() {
    if(siswaData.length === 0) {
        alert('Tidak ada data untuk diimport!');
        return;
    }
    
    // Disable button
    $('#btnImportSiswa').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Memproses...');
    
    $.ajax({
        url: 'proses_import_siswa.php',
        type: 'POST',
        data: {
            data: JSON.stringify(siswaData)
        },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#siswaResultMessage').html(`
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle fa-2x float-left mr-3"></i>
                        <div>
                            <strong>Import Berhasil!</strong><br>
                            Total data: ${response.total}<br>
                            Berhasil diimport: <span class="text-success font-weight-bold">${response.success_count}</span><br>
                            Gagal: <span class="text-danger font-weight-bold">${response.error_count}</span>
                            ${response.errors && response.errors.length > 0 ? '<br><small class="text-danger">Detail: ' + response.errors.join(', ') + '</small>' : ''}
                        </div>
                    </div>
                `);
            } else {
                $('#siswaResultMessage').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> 
                        <strong>Import Gagal!</strong><br>
                        ${response.message}
                    </div>
                `);
            }
            $('#siswaPreviewSection').hide();
            $('#siswaResultSection').show();
        },
        error: function(xhr, status, error) {
            $('#siswaResultMessage').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> 
                    Terjadi kesalahan pada server!<br>
                    Error: ${error}
                </div>
            `);
            $('#siswaPreviewSection').hide();
            $('#siswaResultSection').show();
        },
        complete: function() {
            $('#btnImportSiswa').prop('disabled', false).html('<i class="fas fa-database"></i> Import Data ke Database');
        }
    });
}

// ==================== USER ====================
let userData = [];

const userUploadArea = document.getElementById('userUploadArea');
const userFileInput = document.getElementById('userFileInput');

if(userUploadArea) {
    userUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        userUploadArea.classList.add('drag-over');
    });
    
    userUploadArea.addEventListener('dragleave', () => {
        userUploadArea.classList.remove('drag-over');
    });
    
    userUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        userUploadArea.classList.remove('drag-over');
        const file = e.dataTransfer.files[0];
        if(file) handleUserFile(file);
    });
    
    userUploadArea.addEventListener('click', () => {
        userFileInput.click();
    });
}

if(userFileInput) {
    userFileInput.addEventListener('change', (e) => {
        if(e.target.files[0]) handleUserFile(e.target.files[0]);
    });
}

function handleUserFile(file) {
    if(!file.name.match(/\.(xlsx|xls)$/)) {
        alert('File harus berformat .xlsx atau .xls');
        return;
    }
    
    const reader = new FileReader();
    reader.onload = function(e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, {type: 'array'});
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, {header: 1});
        
        userData = jsonData.slice(1).filter(row => row[0] && row[0].toString().trim());
        
        if(userData.length === 0) {
            alert('File Excel kosong!');
            return;
        }
        
        document.getElementById('userFileNameText').innerHTML = file.name;
        document.getElementById('userJumlahData').innerHTML = userData.length;
        document.getElementById('userFileName').style.display = 'block';
        
        previewUserData();
        document.getElementById('userPreviewSection').style.display = 'block';
        document.getElementById('userUploadArea').style.display = 'none';
    };
    reader.readAsArrayBuffer(file);
}

function previewUserData() {
    const tbody = document.getElementById('userPreviewBody');
    tbody.innerHTML = '';
    
    userData.slice(0, 10).forEach((row, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${index + 1}</td>
            <td><code>${escapeHtml(row[0] || '')}</code></td>
            <td>••••••</td>
            <td>${escapeHtml(row[2] || '')}</td>
            <td><span class="badge bg-info">${escapeHtml(row[3] || '')}</span></td>
            <td>${escapeHtml(row[4] || '')}</td>
        `;
        tbody.appendChild(tr);
    });
    
    if(userData.length > 10) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="6" class="text-center text-muted">... dan ${userData.length - 10} data lainnya</td>`;
        tbody.appendChild(tr);
    }
}

function resetUserImport() {
    location.reload();
}

function importUserData() {
    if(userData.length === 0) {
        alert('Tidak ada data untuk diimport!');
        return;
    }
    
    $('#btnImportUser').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Memproses...');
    
    $.ajax({
        url: 'proses_import_user.php',
        type: 'POST',
        data: {
            data: JSON.stringify(userData)
        },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $('#userResultMessage').html(`
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle fa-2x float-left mr-3"></i>
                        <div>
                            <strong>Import Berhasil!</strong><br>
                            Total data: ${response.total}<br>
                            Berhasil diimport: <span class="text-success font-weight-bold">${response.success_count}</span><br>
                            Gagal: <span class="text-danger font-weight-bold">${response.error_count}</span>
                            ${response.errors && response.errors.length > 0 ? '<br><small class="text-danger">Detail: ' + response.errors.join(', ') + '</small>' : ''}
                        </div>
                    </div>
                `);
            } else {
                $('#userResultMessage').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> 
                        <strong>Import Gagal!</strong><br>
                        ${response.message}
                    </div>
                `);
            }
            $('#userPreviewSection').hide();
            $('#userResultSection').show();
        },
        error: function(xhr, status, error) {
            $('#userResultMessage').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> 
                    Terjadi kesalahan pada server!<br>
                    Error: ${error}
                </div>
            `);
            $('#userPreviewSection').hide();
            $('#userResultSection').show();
        },
        complete: function() {
            $('#btnImportUser').prop('disabled', false).html('<i class="fas fa-database"></i> Import Data ke Database');
        }
    });
}

// ==================== DOWNLOAD TEMPLATE ====================
document.getElementById('downloadTemplateSiswa')?.addEventListener('click', function(e) {
    e.preventDefault();
    const templateData = [
        ['NIS', 'Nama Siswa', 'Kelas', 'Unit', 'Status'],
        ['2024001', 'Ahmad Budiman', 'Kelas 1A', 'Madrasah Ibtidaiyah', 'Aktif'],
        ['2024002', 'Siti Aminah', 'Kelas 1A', 'Madrasah Ibtidaiyah', 'Aktif'],
        ['2024003', 'Budi Santoso', 'Kelas 1B', 'Madrasah Ibtidaiyah', 'Aktif'],
        ['2024004', 'Dewi Lestari', 'Kelas 2A', 'Madrasah Ibtidaiyah', 'Aktif'],
        ['2024005', 'Rizki Fadillah', 'Kelas 2A', 'Madrasah Ibtidaiyah', 'Aktif']
    ];
    const ws = XLSX.utils.aoa_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Template Siswa');
    XLSX.writeFile(wb, 'template_siswa.xlsx');
});

document.getElementById('downloadTemplateUser')?.addEventListener('click', function(e) {
    e.preventDefault();
    const templateData = [
        ['Username', 'Password', 'Nama Lengkap', 'Role', 'Unit'],
        ['guru1', '123456', 'Ahmad Guru', 'Guru', 'Madrasah Ibtidaiyah'],
        ['guru2', '123456', 'Siti Guru', 'Guru', 'Madrasah Tsanawiyah'],
        ['kepala1', '123456', 'Kepala Sekolah', 'Kepala', 'Madrasah Ibtidaiyah'],
        ['pimpinan1', '123456', 'Pimpinan Yayasan', 'Pimpinan', 'MIJ'],
        ['admin1', '123456', 'Super Admin', 'Super Admin', 'MIJ']
    ];
    const ws = XLSX.utils.aoa_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Template User');
    XLSX.writeFile(wb, 'template_user.xlsx');
});
</script>
</body>
</html>