@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('tender.penawaran.ulang') }}
@endsection

@section('content')
    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">

        <div class="card border border-agi-100 card-grid min-w-full" data-datatable="false" data-datatable-page-size="10"
            data-datatable-state-save="false" id="penawaran-table"
            data-api-url="{{ route('tender.penawaran.ulang.datatables') }}">
            <div class="card-header bg-agi-50 py-5 flex-wrap" id="basic_settings">
                <h3 class="card-title">
                    Data Penawaran Ulang
                </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 Penawaran Tender" 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>
                        <a class="btn btn-sm btn-light" href="{{ route('tender.penawaran.exportPenawaran') }}"> Export to
                            Excel
                        </a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table class="table table-auto table-border align-middle text-gray-700 font-medium text-sm"
                        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="tanggal_permohonan">
                                    <span class="sort"> <span class="sort-label"> Tanggal Permohonan </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"> User Pemohon </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"> Cabang Pemohon </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="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="status">
                                    <span class="sort"> <span class="sort-label"> Status </span>
                                        <span class="sort-icon"> </span> </span>
                                </th>
                                <th class="min-w-[50px] text-center" data-datatable-column="actions">Action</th>
                            </tr>
                        </thead>
                    </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>
@endsection

@push('scripts')
    <script type="text/javascript">
        function formatDate(date) {
            const day = date.getDate().toString().padStart(2, '0');
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            // Months are 0-indexed
            const year = date.getFullYear();

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

        function getIndonesianMonth(month) {
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
            ];
            return months[month -
                1];
        }

        function capitalizeWords(str) {
            return str.replace(/\b\w/g, function(char) {
                return char.toUpperCase();
            });
        }

        // Function to check the existence of penawaran and update button
        function checkPenawaranExistence(nomor_registrasi) {
            // URL API untuk cek penawaran
            const url = `/api/check-penawaran/${nomor_registrasi}`;

            // Fetch data dari server
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    const actionDiv = document.getElementById(`action-${nomor_registrasi}`);
                    if (data.exists) {
                        // Jika penawaran ada, ganti tombol menjadi "Penawaran Ulang"
                        actionDiv.innerHTML = `
                        <a class="btn btn-sm btn-icon btn-clear btn-warning" title="Detail" href="/tender/penawaran/${nomor_registrasi}/show">
                    <i class="ki-outline ki-abstract-26"></i>
                </a>
                    <a href="/tender/penawaran/${nomor_registrasi}/edit" class="btn btn-sm btn-icon btn-clear btn-info" title="Penawaran">
                        <i class="ki-outline ki-arrow-circle-right"></i>
                    </a>
                    <a href="/tender/penawaran/${nomor_registrasi}/showKirimEmail" class="btn btn-sm btn-icon btn-clear btn-success hidden" title="Kirim Email">
                        <i class="ki-filled ki-paper-plane"></i>
                    </a>
                `;
                    } else {
                        // Jika tidak ada, tampilkan tombol "Tambah Penawaran"
                        actionDiv.innerHTML = `
                    <a href="/tender/penawaran/${nomor_registrasi}/create" class="btn btn-sm btn-icon btn-clear btn-primary" title="Penawaran">
                        <i class="ki-outline ki-arrow-circle-right"></i>
                    </a>
                `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    const actionDiv = document.getElementById(`action-${nomor_registrasi}`);
                    actionDiv.innerHTML = `<span class="text-danger">Error loading action</span>`;
                });
        }
    </script>
    <script type="module">
        const element = document.querySelector('#penawaran-table');
        const searchInput = document.getElementById('search');

        const apiUrl = element.getAttribute('data-api-url');
        const dataTableOptions = {
            apiEndpoint: apiUrl,
            pageSize: 5,
            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();
                    },
                },
                nomor_registrasi: {
                    title: 'Nomor Registrasi',
                },
                tanggal_permohonan: {
                    title: 'Tanggal Permohonan',
                    render: (item, data) => {
                        return `${formatDate(new Date(data.tanggal_permohonan))}`
                    }
                },
                user_id: {
                    title: 'User Pemohon',
                    render: (item, data) => {
                        return `${data.user.name}`;
                    },
                },
                branch_id: {
                    title: 'Cabang Pemohon',
                    render: (item, data) => {
                        return `${data.branch.name}`;
                    },
                },
                debitur_id: {
                    title: 'Debitur',
                    render: (item, data) => {
                        return `${data.debiture.name}`;
                    },
                },
                tujuan_penilaian_id: {
                    title: 'Tujuan Penilaian',
                    render: (item, data) => {
                        return `${data.tujuan_penilaian.name}`;
                    },
                },
                status: {
                    title: 'Status',
                    render: (item, data) => {
                        return capitalizeWords(data.status);
                    }
                },
                actions: {
                    title: 'Action',
                    render: (item, data) => {
                        // Default action button, to be updated later
                        let actionHtml = `
            <div class="flex flex-nowrap justify-center" id="action-${data.nomor_registrasi}">
                <a class="btn btn-sm btn-icon btn-clear btn-secondary" title="Loading..." href="#">
                    <i class="ki-outline ki-loading"></i>
                </a>
            </div>
        `;

                        // Call the checkPenawaranExistence function to update the action button dynamically
                        setTimeout(() => { // Using setTimeout to ensure DOM elements are rendered before updating
                            checkPenawaranExistence(data.nomor_registrasi);
                        }, 0);

                        return actionHtml;
                    }
                }
            },
        };

        let dataTable = new KTDataTable(element, dataTableOptions);
        // Custom search functionality
        searchInput.addEventListener('input', function() {
            const searchValue = this.value.trim();
            dataTable.search(searchValue, true);

        });
    </script>
@endpush
