<?php
require_once '../includes/header.php';
require_once '../includes/navbar.php';

// Cek apakah user sudah login
if (!isset($_SESSION['login'])) {
    header('Location: ../login.php');
    exit;
}

// Proses upload dan import data
$import_result = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file_excel'])) {
    require_once '../vendor/autoload.php'; // Pastikan sudah install PhpSpreadsheet
    require_once '../includes/import_functions.php'; // File fungsi import
    
    $file = $_FILES['file_excel'];
    
    // Validasi file
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $import_result = [
            'success' => false,
            'message' => 'Error uploading file. Error code: ' . $file['error']
        ];
    } else {
        // Validasi ekstensi file
        $allowed_extensions = ['xlsx', 'xls', 'csv'];
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file_extension, $allowed_extensions)) {
            $import_result = [
                'success' => false,
                'message' => 'Format file tidak didukung. Silakan upload file Excel (xlsx, xls) atau CSV.'
            ];
        } else {
            // Proses import
            $import_result = importGtkFromExcel($file['tmp_name'], $file_extension, $conn);
        }
    }
}
?>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-file-import me-2"></i>Import Data GTK</h2>
        <div>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-1"></i> Kembali ke Daftar GTK
            </a>
            <a href="../assets/templates/template_import_gtk.xlsx" class="btn btn-success">
                <i class="fas fa-download me-1"></i> Download Template
            </a>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-8">
            <div class="card border-0 shadow-lg">
                <div class="card-header bg-primary text-white py-3">
                    <h5 class="card-title mb-0"><i class="fas fa-upload me-2"></i>Upload File Excel</h5>
                </div>
                <div class="card-body p-4">
                    <?php if ($import_result): ?>
                        <div class="alert alert-<?php echo $import_result['success'] ? 'success' : 'danger'; ?>">
                            <h5><?php echo $import_result['success'] ? 'Import Berhasil' : 'Import Gagal'; ?></h5>
                            <p><?php echo $import_result['message']; ?></p>
                            
                            <?php if (isset($import_result['stats'])): ?>
                                <div class="mt-3">
                                    <strong>Statistik Import:</strong><br>
                                    - Total data diproses: <?php echo $import_result['stats']['total']; ?><br>
                                    - Berhasil diimport: <?php echo $import_result['stats']['success']; ?><br>
                                    - Gagal diimport: <?php echo $import_result['stats']['failed']; ?><br>
                                    
                                    <?php if (!empty($import_result['stats']['errors'])): ?>
                                        <div class="mt-2">
                                            <strong>Detail Error:</strong>
                                            <ul class="mb-0">
                                                <?php foreach ($import_result['stats']['errors'] as $error): ?>
                                                    <li><?php echo $error; ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST" enctype="multipart/form-data" id="formImport">
                        <div class="mb-4">
                            <label for="file_excel" class="form-label">Pilih File Excel/CSV</label>
                            <input type="file" class="form-control" id="file_excel" name="file_excel" accept=".xlsx,.xls,.csv" required>
                            <div class="form-text">
                                Format file yang didukung: .xlsx, .xls, .csv. 
                                <a href="../assets/templates/template_import_gtk.xlsx">Download template</a> untuk memastikan format benar.
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="skip_header" name="skip_header" value="1" checked>
                                <label class="form-check-label" for="skip_header">
                                    Baris pertama adalah header (abaikan baris pertama)
                                </label>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="update_existing" name="update_existing" value="1">
                                <label class="form-check-label" for="update_existing">
                                    Update data yang sudah ada (berdasarkan NIP/NUPTK/NIK)
                                </label>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-upload me-1"></i> Import Data
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card border-0 shadow-lg">
                <div class="card-header bg-info text-white py-3">
                    <h5 class="card-title mb-0"><i class="fas fa-info-circle me-2"></i>Panduan Import</h5>
                </div>
                <div class="card-body">
                    <h6>Format Kolom yang Diperlukan:</h6>
                    <ol class="small">
                        <li><strong>NIP</strong> (opsional, bisa kosong atau '-')</li>
                        <li><strong>NUPTK</strong> (opsional, bisa kosong atau '-')</li>
                        <li><strong>NIK</strong> (wajib, harus unik)</li>
                        <li><strong>Nama</strong> (wajib)</li>
                        <li><strong>Tempat Lahir</strong> (wajib)</li>
                        <li><strong>Tanggal Lahir</strong> (wajib, format: YYYY-MM-DD)</li>
                        <li><strong>Jenis Kelamin</strong> (wajib: L/P)</li>
                        <li><strong>Agama</strong> (wajib: Islam/Kristen/Katolik/Hindu/Budha/Khonghucu/Lainnya)</li>
                        <li><strong>Status Pernikahan</strong> (wajib: Belum Kawin/Kawin/Cerai Hidup/Cerai Mati)</li>
                        <li><strong>Alamat</strong> (wajib)</li>
                        <li><strong>No HP</strong> (wajib)</li>
                        <li><strong>Email</strong> (opsional)</li>
                        <li><strong>Sumber Gaji</strong> (wajib: APBN/APBD/Sekolah/Yayasan/Lainnya)</li>
                        <li><strong>Jenis GTK</strong> (wajib: Guru Mapel/Guru BK/Kepala Sekolah/Tendik/Lainnya)</li>
                        <li><strong>Status Kepegawaian</strong> (wajib: PNS/PPPK/GTT/PTT)</li>
                        <li><strong>Pendidikan Terakhir</strong> (wajib: SMA/D3/S1/S2/S3)</li>
                        <li><strong>Mata Pelajaran</strong> (opsional)</li>
                        <li><strong>Tunjangan Sertifikasi</strong> (opsional: 1/0)</li>
                        <li><strong>Jabatan Fungsional</strong> (opsional)</li>
                        <li><strong>Golongan</strong> (opsional)</li>
                        <li><strong>TMT Kerja</strong> (opsional, format: YYYY-MM-DD)</li>
                        <li><strong>Status Aktif</strong> (opsional: 1/0, default: 1)</li>
                    </ol>
                    
                    <div class="alert alert-warning mt-3">
                        <strong>Perhatian:</strong> Pastikan format data sesuai untuk menghindari kegagalan import.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const formImport = document.getElementById('formImport');
    
    formImport.addEventListener('submit', function(e) {
        const fileInput = document.getElementById('file_excel');
        const file = fileInput.files[0];
        
        if (!file) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Peringatan',
                text: 'Silakan pilih file Excel/CSV terlebih dahulu.'
            });
            return;
        }
        
        // Tampilkan loading
        Swal.fire({
            title: 'Memproses Import',
            text: 'Sedang mengimport data, harap tunggu...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    });
});
</script>
<script>
        function downloadTemplate() {
            // Data untuk template
            const data = [
                [
                    "NIP", "NUPTK", "NIK", "Nama", 
                    "Tempat Lahir", "Tanggal Lahir", "Jenis Kelamin", "Agama",
                    "Status Pernikahan", "Alamat", "No HP", "Email",
                    "Sumber Gaji", "Jenis GTK", "Status Kepegawaian", "Pendidikan Terakhir",
                    "Mata Pelajaran", "Tunjangan Sertifikasi", "Jabatan Fungsional", "Golongan",
                    "TMT Kerja", "Status Aktif"
                ],
                [
                    "198506102010051002", "8643564663200043", "3505184501750002", "Ahmad Surya Dinata, S.Pd",
                    "Malang", "1985-06-10", "L", "Islam",
                    "Kawin", "Jl. Raya Bromo No. 123, Malang", "081234567890", "ahmad.surya@sekolah.sch.id",
                    "APBN", "Guru Mapel", "PNS", "S1",
                    "Matematika", "1", "Guru Pertama", "III/a",
                    "2010-07-01", "1"
                ],
                [
                    "199008152015052001", "7654321098765432", "3505209008750001", "Dewi Sartika, S.Pd",
                    "Surabaya", "1990-08-15", "P", "Islam",
                    "Kawin", "Jl. Diponegoro No. 45, Surabaya", "081398765432", "dewi.sartika@sekolah.sch.id",
                    "APBN", "Guru Mapel", "PNS", "S1",
                    "Bahasa Indonesia", "1", "Guru Muda", "III/b",
                    "2015-08-15", "1"
                ],
                [
                    "-", "-", "3505017012850003", "Budi Santoso",
                    "Probolinggo", "1985-12-17", "L", "Kristen",
                    "Belum Kawin", "Jl. Merdeka No. 78, Probolinggo", "085678901234", "",
                    "Sekolah", "Tendik", "GTT", "SMA",
                    "", "0", "", "",
                    "2018-03-10", "1"
                ]
            ];
            
            // Buat workbook
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet(data);
            
            // Atur lebar kolom
            const colWidths = [
                {wch: 20}, {wch: 20}, {wch: 20}, {wch: 25},
                {wch: 15}, {wch: 15}, {wch: 15}, {wch: 15},
                {wch: 15}, {wch: 30}, {wch: 15}, {wch: 25},
                {wch: 15}, {wch: 15}, {wch: 20}, {wch: 20},
                {wch: 20}, {wch: 20}, {wch: 20}, {wch: 10},
                {wch: 15}, {wch: 15}
            ];
            ws['!cols'] = colWidths;
            
            // Tambahkan worksheet ke workbook
            XLSX.utils.book_append_sheet(wb, ws, "Data GTK");
            
            // Buat sheet petunjuk
            const instructionData = [
                ["PETUNJUK PENGGUNAAN TEMPLATE IMPORT DATA GTK"],
                [""],
                ["1. Jangan mengubah urutan kolom atau nama header"],
                ["2. Kolom dengan tanda * wajib diisi"],
                ["3. Format tanggal: YYYY-MM-DD (contoh: 2023-12-31)"],
                ["4. Untuk kolom dengan pilihan, gunakan nilai yang sesuai:"],
                ["   - Jenis Kelamin: L atau P"],
                ["   - Agama: Islam, Kristen, Katolik, Hindu, Budha, Khonghucu, Lainnya"],
                ["   - Status Pernikahan: Belum Kawin, Kawin, Cerai Hidup, Cerai Mati"],
                ["   - Sumber Gaji: APBN, APBD, Sekolah, Yayasan, Lainnya"],
                ["   - Jenis GTK: Guru Mapel, Guru BK, Kepala Sekolah, Tendik, Lainnya"],
                ["   - Status Kepegawaian: PNS, PPPK, GTT, PTT"],
                ["   - Pendidikan Terakhir: SMA, D3, S1, S2, S3"],
                ["5. Untuk Tunjangan Sertifikasi dan Status Aktif: 1 = Ya, 0 = Tidak"],
                ["6. Jika tidak memiliki NIP/NUPTK, isi dengan tanda minus (-)"],
                [""],
                ["Setelah mengisi data, simpan file dan gunakan untuk import di sistem"]
            ];
            
            const wsInstructions = XLSX.utils.aoa_to_sheet(instructionData);
            XLSX.utils.book_append_sheet(wb, wsInstructions, "Petunjuk");
            
            // Simpan file
            const fileName = "template_import_gtk.xlsx";
            XLSX.writeFile(wb, fileName);
            
            alert("Template berhasil diunduh. Silakan buka file " + fileName);
        }
    </script>

<?php
require_once '../includes/footer.php';
?>