@extends('layouts.main')
@section('breadcrumbs')
    {{ Breadcrumbs::render('activity.progres') }}
@endsection
@section('content')
    @push('styles')
        <style>
            .dropdown {
                position: relative;
                display: inline-block;
            }

            .dropdowns-content {
                display: none;
                position: absolute;
                background-color: white;
                min-width: 224px;
                box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
                z-index: 1;
            }

            .dropdown:hover .dropdowns-content {
                display: block;
            }

            .dropdowns-content a {
                color: black;
                padding: 12px 16px;
                text-decoration: none;
                display: block;
            }

            .dropdowns-content a:hover {
                background-color: #f1f1f1;
            }

            .break-words {
                word-break: break-word;
                white-space: normal;
            }
        </style>
    @endpush

    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">
        <div class="card border border-agi-100 min-w-full">
            <div class="card-header bg-agi-50">
                <h3 class="card-title">Team Activity</h3>
            </div>
            <div data-accordion="true">
                @php
                    $sortedTeamsActivity = $teamsActivity->sortBy(function ($item) {
                        return $item->team->regions->penilaiTeam
                            ->filter(function ($penilaiTeam) {
                                $permohonan = optional($penilaiTeam->penilaian)->permohonan;
                                return $permohonan !== null;
                            })
                            ->count();
                    });
                @endphp

                @foreach ($sortedTeamsActivity as $index => $item)
                    @php
                        $totalTask = countPermohonanForUser($item->user->id);
                    @endphp
                    <div class="accordion-item [&:not(:last-child)]:border-b border-b-gray-200" data-accordion-item="true"
                        id="accordion_{{ $index }}">
                        <button class="accordion-toggle py-4 group mx-8"
                            data-accordion-toggle="#accordion_{{ $index }}content_{{ $index }}"
                            style="margin-start: 10px">
                            <table class="table table-auto align-middle text-gray-700 font-medium text-sm">
                                <tr>
                                    <th class="min-w-[150px]" style="width: 600px">
                                        <span
                                            class="text-base text-gray-900 font-medium break-words">{{ $item->user->name }}</span>
                                    </th>
                                    <th class="min-w-[150px]">
                                        <span class="text-base text-gray-900 font-normal">

                                            @if ($totalTask >= 0 && $totalTask < 5)
                                                <span class="badge badge-outline badge-success rounded-full">Total Task
                                                    {{ $totalTask }}</span>
                                            @elseif ($totalTask >= 5 && $totalTask < 10)
                                                <span class="badge badge-outline  badge-warning rounded-full">Total Task
                                                    {{ $totalTask }}</span>
                                            @else
                                                <span class="badge badge-outline  badge-danger rounded-full">Total Task
                                                    {{ $totalTask }}</span>
                                            @endif
                                        </span>
                                    </th>
                                    <th>
                                        <i
                                            class="ki-outline ki-plus text-gray-600 text-2sm font-medium accordion-active:hidden block"></i>
                                        <i
                                            class="ki-outline ki-minus text-gray-600 text-2sm font-medium accordion-active:block hidden"></i>
                                    </th>
                                </tr>

                            </table>
                        </button>
                        <div class="accordion-content hidden" id="accordion_{{ $index }}content_{{ $index }}">
                            <div class="mx-8 pb-4" style="margin-bottom: 20px">
                                <div class="card border border-agi-100 card-grid min-w-full" data-datatable="false"
                                    id="activity-table-{{ $index }}"
                                    data-api-url="{{ route('activity.progres.datatables', ['id' => $item->user->id]) }}">
                                    <div class="card-body">
                                        <div class="scrollable-x-auto">
                                            <table
                                                class="table table-auto align-middle text-gray-700 font-medium text-sm mb-4"
                                                data-datatable-table="true">
                                                <thead>
                                                    <tr>
                                                        <th class="min-w-[100px]">Nama Debitur</th>
                                                        <th class="min-w-[100px]">Tujuan Penilaian</th>
                                                        <th class="min-w-[100px]">Status Bayar</th>
                                                        <th class="min-w-[100px]">Jenis Asset</th>
                                                        <th class="min-w-[100px]">Penugasan</th>
                                                        <th class="min-w-[100px]">Jenis Report</th>
                                                        <th class="min-w-[100px]">Tgl Register</th>
                                                        <th class="min-w-[100px]">Tgl Assign</th>
                                                        <th class="min-w-[100px]">Tgl Kunjungan</th>
                                                        <th class="min-w-[100px]">Progress</th>
                                                        <th class="min-w-[100px]">SLA Laporan</th>
                                                        <th class="min-w-[100px]">SLA Paparan</th>
                                                        <th class="min-w-[100px]">Approve</th>
                                                        <th class="min-w-[50px] text-center">Keterangan</th>
                                                        <th class="min-w-[50px] text-center">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>

                                                </tbody>
                                            </table>
                                        </div>
                                        <div
                                            class="card-footer justify-center md:justify-between flex-col md:flex-row gap-3 text-gray-600 text-2sm font-medium">
                                            <div class="flex items-center gap-2">
                                                Show
                                                <select class="select select-sm w-16" data-datatable-size="true"
                                                    name="perpage"></select> per page
                                            </div>
                                            <div class="flex items-center gap-4">
                                                <span data-datatable-info="true"></span>
                                                <div class="pagination" data-datatable-pagination="true"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="module">
        document.addEventListener('DOMContentLoaded', () => {
            const accordions = document.querySelectorAll('[data-accordion-item]');

            accordions.forEach((accordion, index) => {
                accordion.querySelector('.accordion-toggle').addEventListener('click', () => {
                    const apiUrl = accordion.querySelector('.card-grid').getAttribute(
                        'data-api-url');

                    const dataTableOptions = {
                        apiEndpoint: apiUrl,
                        pageSize: 5,
                        order: [{
                            column: 'nomor_registrasi',
                            dir: 'asc'
                        }],
                        columns: {
                            nama_debitur: {
                                title: 'Nama Debitur',
                                render: (item, data) => {
                                    return `${data.permohonan.debiture?.name}`
                                },
                            },
                            tujuan_penilaian: {
                                title: 'Tujuan Penilaian',
                                render: (item, data) => {
                                    return `${data.permohonan.tujuan_penilaian?.name || ''}`;
                                },
                            },
                            status_bayar: {
                                title: 'Status Bayar',
                                render: (item, data) => {
                                    const status = data.permohonan.status_bayar.replace(
                                        /_/g,
                                        ' ');
                                    const statusClass = data.permohonan.status_bayar ===
                                        'belum_bayar' ? 'text-red-600' :
                                        'text-green-600';
                                    return `<span class="badge badge-sm badge-default font-bold ${statusClass} uppercase">
                            ${status}
                            </span>`;
                                },
                            },
                            jenis_asset: {
                                title: 'Jenis Asset',
                                render: (item, data) =>
                                    `${data.permohonan.debiture?.documents?.map(d => d.jenis_jaminan.name) || ''}`,
                            },
                            penugasan: {
                                title: 'Penugasan',
                                render: (item, data) => {

                                    const roles = data.user_penilai?.map(d => d.role).join(
                                        '<br>') || '-';
                                    return roles;
                                },
                            },
                            jenis_report: {
                                title: 'Jenis Report',
                                render: (item, data) => {
                                    return data.permohonan.penilai?.type_penilai || '-';
                                },
                            },
                            register: {
                                title: 'Register',
                                render: (item, data) =>
                                    `${window.formatTanggalIndonesia(data.permohonan.created_at) || ''}`,

                            },
                            assign: {
                                title: 'Assign',
                                render: (item, data) =>
                                    `${window.formatTanggalIndonesia(data.created_at)}`,
                            },
                            tanggal_kunjungan: {
                                title: 'Tgl Kunjungan',
                                render: (item, data) =>
                                    `${window.formatTanggalIndonesia(data.waktu_penilaian) || ''}`,
                            },
                            progress: {
                                title: 'Progress',
                                render: (item, data) => {
                                    return `<span class="badge badge-sm badge-default uppercase flex justify-center ">${data.permohonan.status}</span>`;
                                }
                            },
                            // tanggal kunjungan h+2 jika plafon di
                            due_date: {
                                title: 'Due Date',
                                render: (item, data) => {
                                    if (!data.due_date_sla) {
                                        return ``;
                                    }
                                    return `${window.formatTanggalIndonesia(data.due_date_sla)}`;
                                }
                            },
                            due_date: {
                                title: 'Due Date SLA',
                                render: (item, data) => {
                                    if (!data.due_date_sla) {
                                        return `-`;
                                    }
                                    return `${window.formatTanggalIndonesia(data.due_date_sla)}`;
                                },
                            },

                            paparan: {
                                title: 'Paparan',
                                render: (item, data) => {
                                    if (!data.due_date_sla) {
                                        return `-`;
                                    }
                                    return `${window.formatTanggalIndonesia(data.paparan)}`;
                                }
                            },
                            approve: {
                                title: 'Approve',
                                render: (item, data) => {
                                    // Gabungkan nama dengan <br> untuk pemisah baris baru
                                    let dataHtml = `
            ${data.permohonan?.approve_so?.name || ''}
            <br>
            ${data.permohonan?.approve_eo?.name || ''}
            <br>
            ${data.permohonan?.approve_dd?.name || ''}
        `;
                                    return dataHtml;
                                },
                            },


                            keterangan: {
                                title: 'Keterangan',
                                render: (item, data) => `${data.keterangan || ''}`,
                            },
                            actions: {
                                title: 'Action',
                                render: (item, data) => {
                                    const roles = data.user_penilai.map(d => d.role)
                                    let htmlData = ''

                                   htmlData = `<a class="btn btn-sm btn-icon btn-clear btn-primary" onclick="updateTeam(${data.user_penilai[0].penilaian_id}, ${data.permohonan.id}, ${data.user_penilai[0].user_id}, ${data.user_penilai[0].team_id}, '${roles}')" title="Ganti Team">
                               <i class="ki-filled ki-user-edit"></i>
                            </a>`

                                    return htmlData;
                        },
                            },
                        },
                    };

                    // Initialize DataTable only for the active accordion
                    if (!accordion.querySelector('.dataTable')) {
                        const element = accordion.querySelector('.card-grid');
                        new KTDataTable(element, dataTableOptions);
                    }
                });
            });
        });


        function formatDateFromISO(isoDateString) {
            const date = new Date(isoDateString);
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = String(date.getFullYear()).slice(-2);
            return `${day}-${month}-${year}`;
        }


        function calculateDateSLA($jenis, $date) {
            let date = new Date($date);
            return $jenis, $date;
        }
    </script>

    <script type="text/javascript">
        function updateTeam(penilaaniId, permohonanId, userId, teamId, roles) {


    const selectCategory = () => {
        Swal.fire({
            title: 'Pilih Kategori',
            html: `
                <select id="categorySelect" class="input">
                    <option value="" selected disabled>Pilih kategori Pengganti</option>
                    <option value="team">Pilih dari Team</option>
                    <option value="region">Pilih dari Wilayah</option>
                </select>
            `,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Lanjut',
            cancelButtonText: 'Batal',
            preConfirm: () => {
                const selectedCategory = document.getElementById('categorySelect').value;
                if (!selectedCategory) {
                    Swal.showValidationMessage('Anda harus memilih kategori!');
                }
                return selectedCategory;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const selectedCategory = result.value;
                let subOptionsHtml = '';

                if (selectedCategory === 'team') {
                    if (roles === 'surveyor' || roles === 'penilai') {
                        subOptionsHtml = `
                            <div class="flex grid gap-2">
                                <select id="subOptionsPenugasan" class="input" disabled>
                                    <option value="${roles}" selected>${roles}</option>
                                </select>
                                <select id="subOptionsSelect" class="input">
                                    <option value="" selected disabled>Pilih Anggota Tim</option>
                                    @foreach ($teamsActivity as $item)
                                    <option value="{{ $item->user->id }}">{{ $item->user->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        `;
                    } else {
                        subOptionsHtml = `
                            <div class="flex grid gap-2">
                                <select id="subOptionsPenugasan" class="input">
                                    <option value="" selected disabled>Pilih Penugasan</option>
                                    <option value="surveyor">Surveyor</option>
                                    <option value="penilai">Penilai</option>
                                    <option value="sama">Penilai dan Surveyor Sama</option>
                                </select>
                                <select id="subOptionsSelect" class="input">
                                    <option value="" selected disabled>Pilih Anggota Tim</option>
                                    @foreach ($teamsActivity as $item)
                                    <option value="{{ $item->user->id }}">{{ $item->user->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        `;
                    }
                } else if (selectedCategory === 'region') {
                    if (roles === 'surveyor' || roles === 'penilai') {
                        subOptionsHtml = `
                            <div class="flex grid gap-2">
                                <select id="subOptionsPenugasan" class="input" disabled>
                                    <option value="${roles}" selected>${roles}</option>
                                </select>
                                <select id="subOptionsSelect" class="input">
                                    <option value="" selected disabled>Pilih Anggota Tim</option>
                                    @foreach ($teamsActivity as $item)
                                    <option value="{{ $item->user->id }}">{{ $item->user->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        `;
                    } else {
                    subOptionsHtml = `
                        <div class="flex grid gap-2">
                            <select id="subOptionsPenugasan" class="input">
                                    <option value="" selected disabled>Pilih Penugasan</option>
                                    <option value="surveyor">Surveyor</option>
                                    <option value="penilai">Penilai</option>
                                    <option value="sama">Penilai dan Surveyor Sama</option>
                                </select>
                            <select id="subOptionsSelect" class="input">
                                <option value="" selected disabled>Pilih Wilayah</option>
                                @foreach ($teamPenilai as $item)
                                    <option value="{{ $item->regions->id }}">{{ $item->regions->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    `;
                    }
                }

                Swal.fire({
                    title: `Pilih ${selectedCategory === 'team' ? 'Anggota Tim' : 'Wilayah'}`,
                    html: subOptionsHtml,
                    icon: 'info',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ya',
                    cancelButtonText: 'Kembali',
                    preConfirm: () => {
                        const subOptionsPenugasan = document.getElementById('subOptionsPenugasan')?.value;
                        const subSelected = document.getElementById('subOptionsSelect').value;
                        if (!subSelected) {
                            Swal.showValidationMessage('Anda harus memilih opsi!');
                            return false;
                        }

                        return {
                            penugasan: subOptionsPenugasan || null,
                            selectedOption: subSelected || null,
                        };
                    }
                }).then((subResult) => {

                    console.log(subResult);

                    if (subResult.dismiss === Swal.DismissReason.cancel) {
                        selectCategory();
                    } else if (subResult.isConfirmed) {
                        if (!subResult.value) {
                            Swal.fire('Error!', 'Anda harus memilih opsi sebelum melanjutkan.', 'error');
                            return;
                        }

                        let token = "{{ csrf_token() }}";
                        let useURL = "{{ URL::to('/activity/update-team') }}";
                        const paramKey = selectedCategory === 'team' ? 'team_member_id' : 'region_id';

                        let input_data = {
                            _token: token,
                            id: penilaaniId,
                            [paramKey]: subResult.value.selectedOption,
                            penugasan: subResult.value.penugasan,
                            permohonan_id: permohonanId,
                            user_id: userId,
                            team_id: teamId,
                        };

                        $.ajax({
                            url: useURL,
                            type: "PUT",
                            cache: false,
                            data: input_data,
                            dataType: "json",
                            success: function(response) {
                                if (response.status === 'success') {
                                    Swal.fire('Sukses!', response.message, 'success').then(() => {
                                        location.reload(true);
                                    });
                                } else {
                                    Swal.fire('Error!', response.message, 'error');
                                }
                            },
                            error: function(xhr) {
                                console.error(xhr);
                                Swal.fire('Error!', 'Terjadi kesalahan saat memproses permintaan.', 'error');
                            },
                        });
                    }
                });
            }
        });
    };

    selectCategory();
}

    </script>
@endpush
