
<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
    <div class="max-w-6xl mx-auto p-6">
        <div class="mb-6">
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Import Pembayaran Angsuran</h1>
            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                Import data pembayaran angsuran dari sistem lama
            </p>
        </div>

        <!-- Download Template -->
        <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-blue-800 dark:text-blue-300">Belum punya template?</p>
                    <p class="text-xs text-blue-600 dark:text-blue-400">Download template Excel untuk mengisi data
                        pembayaran</p>
                </div>
                <a href="<?php echo e(route('import.pembayaran-angsuran.template')); ?>"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700 transition flex items-center gap-2">
                    <i data-lucide="download" class="w-4 h-4"></i>
                    Download Template
                </a>
            </div>
        </div>

        <!-- Informasi Import -->
        <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 mb-6">
            <div class="flex items-center gap-3">
                <i data-lucide="info" class="w-5 h-5 text-green-600"></i>
                <div>
                    <p class="text-sm font-medium text-green-800 dark:text-green-300">Informasi Import Pembayaran</p>
                    <p class="text-xs text-green-600 dark:text-green-400">
                        • Hanya data PEMBAYARAN yang akan diupdate (dibayar, sisa, tanggal_bayar, metode, tanggal
                        validasi bayar)<br>
                        • Status RENCANA ANGSURAN tidak akan berubah (sesuai data awal/generate)<br>
                        • Semua pembayaran akan LANGSUNG DIVALIDASI (pembayaran_valid = valid) <br>
                        • Metode Pembayaran terdiri dari Tunai / Cash, Transfer Bank BNI, Beasiswa / Internal, VA BNI dan QRIS (Gopay/OVO/Dana/LinkAja)
                    </p>
                </div>
            </div>
        </div>

        <!-- Form Upload -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 mb-6">
            <form id="importForm" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <div class="md:col-span-3">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            File Excel <span class="text-red-500">*</span>
                        </label>
                        <input type="file" name="file" id="fileInput" accept=".xlsx,.xls" required
                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Default Tanggal Bayar
                        </label>
                        <input type="date" name="default_tanggal_bayar" id="defaultTanggalBayar"
                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700"
                            value="<?php echo e(date('Y-m-d')); ?>">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Default Metode Pembayaran
                        </label>
                        <select name="default_metode_pembayaran_id" id="defaultMetodePembayaran"
                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700">
                            <option value="">-- Pilih Metode --</option>
                            <?php $__currentLoopData = $metodePembayaran; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $metode): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($metode->id); ?>"><?php echo e($metode->nama); ?> (<?php echo e($metode->kode); ?>)</option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                </div>

                <div class="flex justify-end gap-3">
                    <button type="button" onclick="resetForm()"
                        class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 transition">
                        Reset
                    </button>
                    <button type="submit" id="previewBtn"
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition flex items-center gap-2">
                        <i data-lucide="eye" class="w-4 h-4"></i>
                        Preview Data
                    </button>
                </div>
            </form>
        </div>

        <!-- Preview Table -->
        <div id="previewSection" class="hidden bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden">
            <div class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                <h3 class="font-semibold text-gray-900 dark:text-white">Preview Data</h3>
                <button type="button" id="importBtn"
                    class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition flex items-center gap-2">
                    <i data-lucide="check-circle" class="w-4 h-4"></i>
                    Import Data
                </button>
            </div>
            <div class="overflow-x-auto max-h-96 overflow-y-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700 sticky top-0">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">NIM</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kode Biaya</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Komponen</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Total</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Dibayar</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Sisa</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tgl Bayar</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tgl Validasi Bayar</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        </tr>
                    </thead>
                    <tbody id="previewTableBody" class="divide-y divide-gray-200 dark:divide-gray-700">
                    </tbody>
                </table>
            </div>
            <div id="errorSummary" class="p-4 bg-red-50 dark:bg-red-900/20 border-t border-red-200 hidden"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let previewData = [];

        function resetForm() {
            document.getElementById('fileInput').value = '';
            document.getElementById('previewSection').classList.add('hidden');
            previewData = [];
        }

        document.getElementById('importForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const previewBtn = document.getElementById('previewBtn');

            previewBtn.disabled = true;
            previewBtn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Memproses...';

            try {
                const response = await fetch('<?php echo e(route('import.pembayaran-angsuran.preview')); ?>', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    },
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    previewData = result.preview;
                    renderPreviewTable(result);
                    document.getElementById('previewSection').classList.remove('hidden');

                    if (result.error_count > 0) {
                        document.getElementById('errorSummary').innerHTML = `
                            <div class="text-sm text-red-600">
                                <strong>Error (${result.error_count}):</strong><br>
                                ${result.errors.join('<br>')}
                            </div>
                        `;
                        document.getElementById('errorSummary').classList.remove('hidden');
                    } else {
                        document.getElementById('errorSummary').classList.add('hidden');
                        Swal.fire('Sukses', `${result.success_count} data siap diimport`, 'success');
                    }
                } else {
                    Swal.fire('Error', result.message || 'Terjadi kesalahan', 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Gagal memproses data: ' + error.message, 'error');
            } finally {
                previewBtn.disabled = false;
                previewBtn.innerHTML = '<i data-lucide="eye" class="w-4 h-4"></i> Preview Data';
                lucide.createIcons();
            }
        });

        function renderPreviewTable(result) {
            const tbody = document.getElementById('previewTableBody');

            if (result.preview.length === 0) {
                tbody.innerHTML =
                    '<tr><td colspan="10" class="text-center py-8 text-gray-500">Tidak ada data valid</td></tr>';
                document.getElementById('importBtn').disabled = true;
                return;
            }

            tbody.innerHTML = result.preview.map((item, index) => {
                const statusClass = item.sisa_setelah === 0 ? 'text-green-600' : 'text-yellow-600';
                const statusText = item.sisa_setelah === 0 ? 'LUNAS' : 'CICILAN';

                return `
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-4 py-2 text-sm">${index + 1}</td>
                        <td class="px-4 py-2 text-sm font-mono">${escapeHtml(item.nim)}</td>
                        <td class="px-4 py-2 text-sm">${escapeHtml(item.nama)}</td>
                        <td class="px-4 py-2 text-sm font-mono">${escapeHtml(item.kode_biaya)}</td>
                        <td class="px-4 py-2 text-sm">${escapeHtml(item.komponen)}</td>
                        <td class="px-4 py-2 text-sm text-right">${formatRupiah(item.total_tagihan)}</td>
                        <td class="px-4 py-2 text-sm text-right font-bold text-blue-600">${formatRupiah(item.total_dibayar)}</td>
                        <td class="px-4 py-2 text-sm text-right ${statusClass}">${formatRupiah(item.sisa_setelah)}</td>
                        <td class="px-4 py-2 text-sm">${item.tanggal_bayar}</td>
                        <td class="px-4 py-2 text-sm">${item.tanggal_validasi_bayar || '-'}</td>
                        <td class="px-4 py-2 text-sm">
                            <span class="px-2 py-1 rounded-full text-xs font-medium ${item.sisa_setelah === 0 ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                                ${statusText}
                            </span>
                        </td>
                    </tr>
                `;
            }).join('');

            document.getElementById('importBtn').disabled = false;
        }

        document.getElementById('importBtn').addEventListener('click', async function() {
            if (previewData.length === 0) {
                Swal.fire('Info', 'Tidak ada data yang akan diimport', 'info');
                return;
            }

            const importData = previewData.map(item => ({
                detail_id: item.detail_id,
                total_dibayar: item.total_dibayar,
                tanggal_bayar: item.tanggal_bayar,
                metode_pembayaran_id: item.metode_pembayaran_id,
                tanggal_validasi_bayar: item.tanggal_validasi_bayar,
            }));

            const totalNominal = previewData.reduce((sum, item) => sum + item.total_dibayar, 0);

            Swal.fire({
                title: 'Konfirmasi Import',
                html: `
                    <div class="text-left">
                        <p>Anda akan mengimport:</p>
                        <div class="bg-gray-100 dark:bg-gray-800 p-3 rounded-lg mt-2">
                            <div class="flex justify-between mb-1">
                                <span>Jumlah Transaksi:</span>
                                <span class="font-bold">${previewData.length} item</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Total Pembayaran:</span>
                                <span class="font-bold text-green-600">Rp ${formatRupiah(totalNominal)}</span>
                            </div>
                        </div>
                        <p class="text-xs text-red-500 mt-3">⚠️ Data yang diimport TIDAK DAPAT DIURUNGKAN!</p>
                    </div>
                `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Import Sekarang',
                cancelButtonText: 'Batal',
                confirmButtonColor: '#10b981'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    const importBtn = document.getElementById('importBtn');
                    importBtn.disabled = true;
                    importBtn.innerHTML =
                        '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Mengimport...';

                    try {
                        const response = await fetch(
                            '<?php echo e(route('import.pembayaran-angsuran.process')); ?>', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                                },
                                body: JSON.stringify({
                                    data: importData
                                })
                            });

                        const result = await response.json();

                        if (result.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Import Berhasil!',
                                html: `Berhasil import ${result.imported} pembayaran${result.failed > 0 ? `<br><span class="text-red-500">${result.failed} gagal</span>` : ''}`,
                                confirmButtonColor: '#4f46e5'
                            });
                            resetForm();
                        } else {
                            Swal.fire('Import Gagal', result.message, 'error');
                        }
                    } catch (error) {
                        Swal.fire('Error', error.message, 'error');
                    } finally {
                        importBtn.disabled = false;
                        importBtn.innerHTML =
                            '<i data-lucide="check-circle" class="w-4 h-4"></i> Import Data';
                        lucide.createIcons();
                    }
                }
            });
        });

        function formatRupiah(angka) {
            return new Intl.NumberFormat('id-ID').format(angka || 0);
        }

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

        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();
        });
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH C:\Users\User\Documents\K2-PROJECTS\k2-sipema\resources\views/import/pembayaran-angsuran.blade.php ENDPATH**/ ?>