@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('memo.index') }}
@endsection

@section('content')
    <div class="grid gap-5 mx-auto w-full lg:gap-7.5">
        <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="memo-table" data-api-url="{{ route('memo.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Memo Penyelesaian
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex gap-2">
                        <label class="input input-sm"> <i class="ki-filled ki-magnifier"> </i>
                            <input placeholder="Search Memo Penyelesaian" id="search" type="text" value="">
                        </label>
                        <select class="select select-sm" id="filter-jenis-penilaian">
                            <option value="">Semua Jenis Penilaian</option>
                            <option value="1">Internal</option>
                            <option value="2">External</option>
                        </select>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>
                        <button class="btn btn-sm btn-primary" id="btn-create-memo" disabled>
                            <i class="ki-filled ki-plus"></i>
                            Buat Memo Penyelesaian
                        </button>
                        <a class="btn btn-sm btn-light" href="#"> Export to 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"
                        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-[150px]" data-datatable-column="nomor_registrasi">
                                    <span class="sort"> <span class="sort-label"> Nomor Registrasi </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="debitur_id">
                                    <span class="sort"> <span class="sort-label"> Debitur </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="branch_id">
                                    <span class="sort"> <span class="sort-label"> Pemohon(Cabang/Direktorat) </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="user_id">
                                    <span class="sort"> <span class="sort-label"> AO </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="jenis_penilaian_id">
                                    <span class="sort"> <span class="sort-label"> Jenis Penilaian </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="tujuan_penilaian_id">
                                    <span class="sort"> <span class="sort-label"> Tujuan Penilaian </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="jenis_fasilitas_kredit_id">
                                    <span class="sort"> <span class="sort-label"> Fasilitas Kredit </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="tanggal_survei">
                                    <span class="sort"> <span class="sort-label"> Tanggal Survei </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[150px]" data-datatable-column="due_date_sla">
                                    <span class="sort"> <span class="sort-label"> Due Date SLA </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px] text-center" data-datatable-column="status">Status</th>
                                <th class="min-w-[50px] text-center" data-datatable-column="actions">Actions</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>
@endsection

@push('scripts')
    <script type="text/javascript">
        /**
         * Format tanggal ke format Indonesia
         * @param {Date} date - Tanggal yang akan diformat
         * @returns {string} - Tanggal dalam format Indonesia
         */
        function formatDate(date) {
            const day = date.getDate().toString().padStart(2, '0');
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const year = date.getFullYear();

            return `${day} ${getIndonesianMonth(month)} ${year}`;
        }

        /**
         * Mendapatkan nama bulan dalam bahasa Indonesia
         * @param {string} month - Nomor bulan
         * @returns {string} - Nama bulan dalam bahasa Indonesia
         */
        function getIndonesianMonth(month) {
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
            ];
            return months[month - 1];
        }
    </script>
    <script type="module">
        const element = document.querySelector('#memo-table');
        const searchInput = document.getElementById('search');
        const filterJenisPenilaian = document.getElementById('filter-jenis-penilaian');
        const btnCreateMemo = document.getElementById('btn-create-memo');
        let selectedItems = [];

        const apiUrl = element.getAttribute('data-api-url');
        const dataTableOptions = {
            apiEndpoint: apiUrl,
            pageSize: 10,
            columns: {
                select: {
                    render: (item, data, context) => {
                        // Cek apakah sudah ada memo penyelesaian
                        const hasMemo = data.noc && data.noc.memo_penyelesaian;

                        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');

                        // Disable checkbox jika sudah ada memo
                        if (hasMemo) {
                            checkbox.disabled = true;
                            checkbox.title = 'Permohonan ini sudah memiliki memo penyelesaian';
                        }

                        return checkbox.outerHTML.trim();
                    },
                },
                nomor_registrasi: {
                    title: 'Nomor Registrasi',
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        if (data.debiture) {
                            return `${data.debiture.name.toUpperCase()}`;
                        }
                        return "-";
                    },
                },
                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => {
                        return `${data.branch.name}`;
                    },
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return `${data.user.name}`;
                    },
                },
                jenis_penilaian_id: {
                    title: 'Jenis Penilaian',
                    render: (item, data) => {
                        return `${data.jenis_penilaian.name}`;
                    }
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => {
                        switch (data.tujuan_penilaian.code) {
                            case "TP0001":
                                return `<span class="badge badge-sm badge-primary">${data.tujuan_penilaian.name}</span>`;
                            case "TP0002":
                                return `<span class="badge badge-sm badge-info">${data.tujuan_penilaian.name}</span>`;
                            case "TP0003":
                                return `<span class="badge badge-sm badge-success">${data.tujuan_penilaian.name}</span>`;
                            case "TP0004":
                                return `<span class="badge badge-sm badge-danger">${data.tujuan_penilaian.name}</span>`;
                            case "TP0005":
                                return `<span class="badge badge-sm badge-warning">${data.tujuan_penilaian.name}</span>`;
                            case "TP0006":
                                return `<span class="badge badge-sm badge-dark">${data.tujuan_penilaian.name}</span>`;
                            case "TP0007":
                                return `<span class="badge badge-sm badge-outline badge-info">${data.tujuan_penilaian.name}</span>`;
                            default:
                                return `<span class="badge badge-sm badge-outline badge-default">${data.tujuan_penilaian.name}</span>`;
                        }
                    },
                },
                jenis_fasilitas_kredit_id: {
                    title: 'Fasilitas Kredit',
                    render: (item, data) => {
                        return `${data.jenis_fasilitas_kredit.name}`;
                    }
                },
                tanggal_survei: {
                    title: 'Tanggal Survei',
                    render: (item, data) => {
                        if (data.penilaian.waktu_penilaian) {
                            return `${formatDate(new Date(data.penilaian.waktu_penilaian))}`;
                        }
                        return `${formatDate(new Date(data.penilaian.created_at))}`;
                    },
                },
                due_date_sla: {
                    title: 'Due Date SLA',
                    render: (item, data) => {
                        const tujuan_penilaian = data.tujuan_penilaian.name;
                        const tipe_laporan = data.penilai?.type;
                        const nilai_plafond = data.penilaian.nilaiPlafond?.name;
                        let waktu_penilaian = new Date(data.penilaian.created_at);
                        if (data.penilaian.waktu_penilaian) {
                            waktu_penilaian = new Date(data.penilaian.waktu_penilaian);
                        }

                        if (tujuan_penilaian === "RAP") {
                            waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                        } else {
                            if (tipe_laporan === "sederhana") {
                                waktu_penilaian.setDate(waktu_penilaian.getDate() + 2);
                            } else if (tipe_laporan === "standar") {
                                if (nilai_plafond === "2 M - 5 M") {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                                } else if (nilai_plafond === "< 2M") {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 3);
                                } else {
                                    waktu_penilaian.setDate(waktu_penilaian.getDate() + 5);
                                }
                            }
                        }
                        return formatDate(waktu_penilaian);
                    },
                },
                status: {
                    title: 'Status',
                    render: (item, data) => {
                        let badgeClass = 'badge-default';
                        if (data.status === 'memo-penyelesaian') {
                            badgeClass = 'badge-success';
                        } else if (data.status === 'done') {
                            badgeClass = 'badge-primary';
                        } else if (data.status === 'proses-laporan') {
                            badgeClass = 'badge-warning';
                        }
                        return `<span class="flex justify-center uppercase badge badge-sm ${badgeClass}">${data.status}</span>`;
                    }
                },
                actions: {
                    title: 'Actions',
                    render: (item, data) => {
                        let actionButtons = '';

                        // Cek apakah sudah ada memo penyelesaian dengan PDF
                        if (data.noc && data.noc.memo_penyelesaian) {
                            actionButtons = `
                                <div class="flex flex-col gap-1">
                                    <a href="memo/memo/download-pdf/${data.id}"
                                       class="flex gap-1 items-center btn btn-sm btn-primary"
                                       title="Download PDF Memo Penyelesaian">
                                        <i class="fas fa-download"></i>
                                        Download Memo
                                    </a>
                                </div>`;
                        } else {
                            actionButtons = `
                                <span class="text-sm text-gray-500">Belum ada memo</span>`;
                        }

                        return `<div class="flex flex-wrap gap-1.5 justify-center">${actionButtons}</div>`;
                    },
                }
            },
        };

        let dataTable = new KTDataTable(element, dataTableOptions);

        /**
         * Fungsi untuk menangani perubahan checkbox
         * Mengelola state tombol berdasarkan checkbox yang dipilih
         */
        function handleCheckboxChange() {
            // Hanya ambil checkbox yang tidak disabled dan checked
            const checkboxes = document.querySelectorAll('input[data-datatable-row-check="true"]:checked:not(:disabled)');
            selectedItems = Array.from(checkboxes).map(cb => cb.value);

            // Log untuk debugging
            console.log('Selected items:', selectedItems);

            // Enable/disable tombol berdasarkan jumlah item yang dipilih
            const hasSelection = selectedItems.length > 0;
            btnCreateMemo.disabled = !hasSelection;

            // Update text tombol create memo
            if (hasSelection) {
                btnCreateMemo.textContent = `Buat Memo Penyelesaian (${selectedItems.length} item)`;
            } else {
                btnCreateMemo.textContent = 'Buat Memo Penyelesaian';
            }
        }

        /**
         * Fungsi untuk clear semua checkbox yang terpilih
         * Menghapus semua selection dan reset state tombol
         */
        function clearSelectedCheckboxes() {
            try {
                // Uncheck master checkbox juga - gunakan selector yang lebih spesifik
                const masterCheckbox = document.querySelector('#memo-table thead input[type="checkbox"]');
                if (masterCheckbox) {
                    masterCheckbox.checked = false;
                }
                // Uncheck semua checkbox yang tidak disabled
                const checkboxes = document.querySelectorAll('input[data-datatable-row-check="true"]:not(:disabled)');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });

                // Reset selected items array
                selectedItems = [];

                // Update state tombol
                btnCreateMemo.disabled = true;
                btnCreateMemo.textContent = 'Buat Memo Penyelesaian';

                // Log untuk debugging
                console.log('All checkboxes cleared successfully');

            } catch (error) {
                console.error('Error clearing checkboxes:', error);
            }
        }

        // Event listener untuk checkbox changes
        element.addEventListener('change', function(e) {
            if (e.target.type === 'checkbox') {
                handleCheckboxChange();
            }
        });

        // Event listener untuk tombol create memo
        btnCreateMemo.addEventListener('click', function() {
            if (selectedItems.length > 0) {
                const selectedIds = selectedItems.join(',');
                console.log('Creating memo for IDs:', selectedIds);
                window.location.href = `{{ route('memo.create') }}?selected_ids=${selectedIds}`;
            }
        });

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

        /**
         * Filter berdasarkan jenis penilaian
         * Menggunakan pola yang sama dengan districts filter
         */
        filterJenisPenilaian.addEventListener('change', function() {
            const filterValue = this.value;
            const searchValue = searchInput.value.trim();

            // Gabungkan filter dan search dalam satu parameter
            const combinedSearch = `${filterValue}|${searchValue}`;

            // Log untuk debugging
            console.log('Filter jenis penilaian:', filterValue);
            console.log('Search value:', searchValue);
            console.log('Combined search:', combinedSearch);

            // Gunakan search method seperti di districts
            dataTable.search(combinedSearch, true);
        });

        /**
         * Update search input handler untuk mendukung filter
         */
        searchInput.addEventListener('input', function() {
            const searchValue = this.value.trim();
            const filterValue = filterJenisPenilaian.value;

            // Gabungkan search dan filter
            const combinedSearch = `${filterValue}|${searchValue}`;

            // Log untuk debugging
            console.log('Search input:', searchValue);
            console.log('Current filter:', filterValue);
            console.log('Combined search:', combinedSearch);

            dataTable.search(combinedSearch, true);
        });
    </script>
@endpush
