@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('admin-kredit.slik') }}
@endsection

@section('content')
    <div class="grid">
        <div class="min-w-full border card border-agi-100 card-grid" data-datatable="false" data-datatable-page-size="10"
            data-datatable-state-save="false" id="slik-table" data-api-url="{{ route('admin-kredit.slik.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Data SLIK
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex">
                        <label class="input input-sm">
                            <i class="ki-filled ki-magnifier"></i>
                            <input placeholder="Search SLIK" id="search" type="text" value="">
                        </label>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>

                        <!-- Import Excel -->
                        <button class="btn btn-sm btn-success" data-modal-toggle="#import-modal">
                            <i class="ki-filled ki-file-up"></i> Import Excel
                        </button>

                        <a class="btn btn-sm btn-light" href="#" id="export-excel">
                            <i class="ki-filled ki-file-down"></i> Export Excel
                        </a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table
                        class="table text-sm font-medium text-gray-700 align-middle table-auto table-border min-w-[1200px]"
                        data-datatable-table="true">
                        <thead>
                            <tr>
                                <th class="w-14">
                                    <input class="checkbox checkbox-sm" data-datatable-check="true" type="checkbox" />
                                </th>
                                <th class="min-w-[100px]" data-datatable-column="sandi_bank">
                                    <span class="sort">
                                        <span class="sort-label">Sandi Bank</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[80px]" data-datatable-column="tahun">
                                    <span class="sort">
                                        <span class="sort-label">Tahun</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[120px]" data-datatable-column="no_rekening">
                                    <span class="sort">
                                        <span class="sort-label">No Rekening</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[100px]" data-datatable-column="cif">
                                    <span class="sort">
                                        <span class="sort-label">CIF</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[120px]" data-datatable-column="nama_debitur">
                                    <span class="sort">
                                        <span class="sort-label">Nama Debitur</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[100px]" data-datatable-column="kolektibilitas">
                                    <span class="sort">
                                        <span class="sort-label">Kolektibilitas</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[100px]" data-datatable-column="fasilitas">
                                    <span class="sort">
                                        <span class="sort-label">Fasilitas</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[120px]" data-datatable-column="nilai_agunan">
                                    <span class="sort">
                                        <span class="sort-label">Nilai Agunan</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                                <th class="min-w-[100px]" data-datatable-column="status_agunan">
                                    <span class="sort">
                                        <span class="sort-label">Status</span>
                                        <span class="sort-icon"></span>
                                    </span>
                                </th>
                            </tr>
                        </thead>
                    </table>
                </div>
                <div
                    class="flex-col gap-3 justify-center font-medium text-gray-600 card-footer md:justify-between md:flex-row text-2sm">
                    <div class="flex gap-2 items-center">
                        Show
                        <select class="w-16 select select-sm" data-datatable-size="true" name="perpage"> </select> per page
                    </div>
                    <div class="flex gap-4 items-center">
                        <span data-datatable-info="true"> </span>
                        <div class="pagination" data-datatable-pagination="true">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



    <!-- Modal Import Excel -->
    <div class="modal" data-modal="true" id="import-modal">
        <div class="modal-content max-w-[500px] top-[15%]">
            <div class="modal-header">
                <h3 class="modal-title">Import Data SLIK</h3>
                <button class="btn btn-sm btn-icon btn-light btn-clear shrink-0" data-modal-dismiss="true">
                    <i class="ki-filled ki-cross"></i>
                </button>
            </div>
            <form action="{{ route('admin-kredit.slik.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="flex flex-col gap-5">
                        <div class="flex flex-col gap-2.5">
                            <label class="text-gray-900 form-label">File Excel</label>
                            <input type="file" name="file" class="file-input" accept=".xlsx,.xls,.csv" required>
                            <div class="text-gray-600 text-2sm">
                                Format yang didukung: .xlsx, .xls, .csv (Maksimal 10MB)
                            </div>
                            <div class="text-blue-600 text-2sm">
                                <a href="{{ route('admin-kredit.slik.download-template') }}"
                                    class="underline hover:text-blue-800">
                                    <i class="ki-filled ki-download"></i> Download Template Excel
                                </a>
                            </div>
                        </div>
                        <div class="p-3 bg-yellow-100 rounded border border-yellow-300">
                            <div class="text-sm text-yellow-800">
                                <strong>Catatan:</strong>
                                <ul class="mt-1 list-disc list-inside">
                                    <li>Data akan dimulai dari baris ke-2 (setelah header)</li>
                                    <li>Pastikan urutan kolom sesuai dengan template</li>
                                    <li>Data akan di-update jika sudah ada berdasarkan kombinasi sandi bank, tahun, bulan,
                                        dan no rekening</li>
                                    <li>Kolom yang wajib diisi: Sandi Bank, Tahun, Bulan, No Rekening, CIF</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="flex gap-4">
                        <button type="button" class="btn btn-light" data-modal-dismiss="true">Batal</button>
                        <button type="submit" class="btn btn-primary">Import</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('styles')
    <style>
        /* Responsive adjustments for table */
        @media (max-width: 768px) {
            .table-responsive {
                overflow-x: auto;
            }

            .modal-content {
                max-width: 95% !important;
                margin: 10px;
            }

            .grid-cols-1.md\:grid-cols-2 {
                grid-template-columns: 1fr;
            }
        }

        /* Ensure table is scrollable on small screens */
        .scrollable-x-auto {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        /* Prevent text wrapping in table cells */
        .table th,
        .table td {
            white-space: nowrap;
            vertical-align: middle;
        }

        /* Allow wrapping for long text in detail modal */
        .modal-body .text-gray-900 {
            word-break: break-word;
        }
    </style>
@endpush

@push('scripts')
    <script>
        let dataTable;
    </script>
    <script type="module">
        /**
         * Inisialisasi DataTable untuk SLIK menggunakan KTDataTable
         */
        document.addEventListener('DOMContentLoaded', function() {
            const element = document.querySelector('#slik-table');
            const searchInput = document.getElementById('search');

            const apiUrl = element.getAttribute('data-api-url');

            // Konfigurasi DataTable menggunakan KTDataTable
            const dataTableOptions = {
                apiEndpoint: apiUrl,
                pageSize: 10,
                columns: {
                    select: {
                        render: (item, data, context) => {
                            const checkbox = document.createElement('input');
                            checkbox.className = 'checkbox checkbox-sm';
                            checkbox.type = 'checkbox';
                            checkbox.value = data.id.toString();
                            checkbox.setAttribute('data-datatable-row-check', 'true');
                            return checkbox.outerHTML.trim();
                        },
                    },
                    sandi_bank: {
                        title: 'Sandi Bank',
                    },
                    tahun: {
                        title: 'Tahun',
                        render: (item, data) => {
                            return data.bulan + '-' + data.tahun;
                        }
                    },
                    no_rekening: {
                        title: 'No Rekening',
                    },
                    cif: {
                        title: 'CIF',
                    },
                    nama_debitur: {
                        title: 'Nama Debitur',
                        render: (item, data) => {
                            const nama = data.nama_debitur || '-';
                            return nama.length > 30 ? nama.substring(0, 30) + '...' : nama;
                        },
                    },
                    kolektibilitas: {
                        title: 'Kolektibilitas',
                        render: (item, data) => {
                            return data.kolektibilitas || '-';
                        },
                    },
                    fasilitas: {
                        title: 'Fasilitas',
                        render: (item, data) => {
                            return data.fasilitas || '-';
                        },
                    },
                    nilai_agunan_formatted: {
                        title: 'Nilai Agunan',
                        render: (item, data) => {
                            return data.nilai_agunan_formatted || '-';
                        },
                    },
                    status_badge: {
                        title: 'Status',
                        render: (item, data) => {
                            return data.status_badge || '-';
                        },
                    }
                },
            };

            // Inisialisasi DataTable
            dataTable = new KTDataTable(element, dataTableOptions);
            dataTable.showSpinner();

            // Fungsi pencarian
            searchInput.addEventListener('input', function() {
                const searchValue = this.value.trim();
                dataTable.search(searchValue, true);
            });


            // Export Excel functionality
            document.getElementById('export-excel').addEventListener('click', function(e) {
                e.preventDefault();

                // Build export URL with current filters
                const params = new URLSearchParams();
                if (searchInput.value) params.append('search', searchInput.value);
                const exportUrl = '{{ route('admin-kredit.slik.export') }}?' + params.toString();
                window.open(exportUrl, '_blank');
            });
        });
    </script>

    <script>
        /**
         * Fungsi untuk menampilkan detail data SLIK
         * @param {number} id - ID data SLIK yang akan ditampilkan
         */
        function showDetail(id) {
            // Redirect ke halaman detail
            window.location.href = `{{ route('admin-kredit.slik.show', ':id') }}`.replace(':id', id);
        }

        /**
         * Fungsi untuk memindahkan data SLIK ke laporan
         * @param {number} id - ID data SLIK yang akan dipindahkan
         */
        function moveToLaporan(id) {
            window.Swal.fire({
                title: 'Konfirmasi',
                text: 'Apakah Anda yakin ingin memindahkan data ini ke laporan SLIK?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Pindahkan!',
                cancelButtonText: 'Batal',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    // Tampilkan loading
                    window.Swal.fire({
                        title: 'Memproses...',
                        text: 'Sedang memindahkan data ke laporan SLIK',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        willOpen: () => {
                            window.Swal.showLoading();
                        }
                    });

                    fetch(`{{ route('admin-kredit.laporan-slik.store') }}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                slik_id: id
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            window.Swal.close();

                            if (data.success) {
                                window.Swal.fire({
                                    title: 'Berhasil!',
                                    text: data.message || 'Data berhasil dipindahkan ke laporan SLIK',
                                    icon: 'success',
                                    confirmButtonText: 'OK'
                                }).then(() => {
                                    // Reload tabel DataTable
                                    dataTable.reload();
                                });
                            } else {
                                window.Swal.fire({
                                    title: 'Gagal!',
                                    text: data.message || 'Gagal memindahkan data',
                                    icon: 'error',
                                    confirmButtonText: 'OK'
                                });
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            window.Swal.close();
                            window.Swal.fire({
                                title: 'Error!',
                                text: 'Terjadi kesalahan saat memindahkan data',
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                        });
                }
            });
        }
    </script>
@endpush
