@extends('client.pages.user.tabs')

@section('title', 'History payment')

@section('tab-content')
    <div class="relative flex flex-col min-w-0 break-words bg-white border-0 shadow-soft-xl ">
        <div class="table-responsive ">
            <table class="border-collapse float-right my-[0.2rem]">
                <tbody>
                    <tr>
                        <td class="p-1 float-right text-gray-700 font-bold">From date:</td>
                        <td>
                            <input type="search" id="from_date" name="from_date" class="border p-[2px]">
                        </td>
                    </tr>
                    <tr class="bg-white">
                        <td class="p-1 float-right text-gray-700 font-bold">To date:</td>
                        <td><input type="search" id="to_date" name="to_date" class="border p-[2px]"></td>
                    </tr>
                </tbody>
            </table>
            <table id="table-data"
                class="table table-flush text-slate-500 cell-border compact dt-responsive table-bordered">
                <thead class="thead-light">
                    <tr>
                        @foreach ($columns as $column)
                            <th data-column="{{ $column['name'] }}" @class([
                                'dt-center uppercase' => true,
                                'first:border-l-[1px] border-t-[1px] border-r-[1px]' => true,
                                $column['class'] ?? '' => true,
                            ])> {{ $column['label'] }} </th>
                        @endforeach
                    </tr>
                </thead>
            </table>
        </div>
    </div>
    {{-- example: td-control --}}
    <ul class="clone td-control-data p-4 grid grid-cols-3 gap-2">
        <li class="clone td-control-item-found">
            <span class="mr-2 min-w-15 inline-block" data-td-control="value"></span>
            <span class="bg-green-500 text-white text-xs font-medium me-2 px-2.5 py-0.5 rounded">
                <span data-td-control="count_found"></span>
                <span class="ml-1">serial number(s)</span>
            </span>
        </li>
        <li class="clone td-control-item-not_found">
            <span class="mr-2 min-w-15 inline-block" data-td-control="value"></span>
            <span class="bg-red-500 text-white text-xs font-medium me-2 px-2.5 py-0.5 rounded">
                <span></span>
                <span>Not found</span>
            </span>
        </li>
    </ul>

    @component('components.modal_info')
        @slot('id', 'modal_info')
        @slot('title', 'Show info serial number(s)')

        <div class="p-4 md:p-5 table-sticky">
            <table class="border-collapse border border-gray-300 w-full">
                <thead>
                    <tr>
                        <th class="h-12">#</th>
                        <th>Serial Number/Instance ID</th>
                        <th>Part Number</th>
                        <th>Country of Origin</th>
                        <th>Flag</th>
                        <th>Cover</th>
                        <th>Warranty end</th>
                        <th>End Customer</th>
                    </tr>
                </thead>
                <tbody class="modal_info-data">
                </tbody>
            </table>
        </div>

        {{-- example: Append modal --}}
        <table class="clone">
            <tr class="clone bg-gray-100 modal_info-item">
                <td data-modal_info="#"></td>
                <td class="text-center">
                    <span data-modal_info="_serialNumber"></span>
                    /
                    <span data-modal_info="instanceId"></span>
                </td>
                <td class="text-center" data-modal_info="_partNumber"></td>
                <td class="text-center" data-modal_info="CountryOfOrigin">CN</td>
                <td class="text-center" data-modal_info="disabledLineFlagMsgs.length" data-modal_info_type="bool"></td>
                <td class="text-center" data-modal_info="isCovered"></td>
                <td class="text-center" data-modal_info="warrantyExpiry"></td>
                <td class="text-left">
                    <span data-modal_info="endCustomer.name"></span>
                    (<span data-modal_info="endCustomer.id"></span>)
                    <span data-modal_info="endCustomer.address.country"></span>
                </td>
            </tr>
        </table>
    @endcomponent
@endsection

@include('components.datatable')

@push('script')
    <script>
        const COLUMNS = @json($columns);
        const CLASS = {
            'btn-info': 'px-3 py-2 text-xs font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300',
        }
        const BADGE_YN = {
            NO: '<span class="bg-red-300 text-red-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded">NO</span>',
            YES: '<span class="bg-green-300 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded">YES</span>',
        }
        const MSG = {
            NOT_FOUND: '<span class="bg-red-500 text-white text-xs font-medium me-2 px-2.5 py-0.5 rounded">Not Found</span>',
        }
        const STATUS = {
            0: '<span class="bg-red-300 text-red-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded">FAIL</span>',
            1: '<span class="bg-green-300 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded">COMPLETE</span>',
            2: '<span class="text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded">PENDING...</span>',
        }

        // init datetime input
        window.addEventListener("load", (event) => {
            new DateTime('#from_date');
            new DateTime('#to_date');

            document.querySelectorAll('#from_date, #to_date').forEach((el) => {
                el.addEventListener('change', () => DT.draw());
            });
        });

        function findIndexByColumnName(name) {
            return COLUMNS.findIndex(col => col.name === name)
        }

        function showModalInfoById(id) {
            const data = DT.rows().data().toArray();
            const row = data.find((row) => row[findIndexByColumnName('id')] === id);
            const response = row[findIndexByColumnName('response')]
            if (response) {
                $table = $('.modal_info-data');
                $table.html('');
                response['data'].forEach((item, index) => {
                    let $tr = $('.clone.modal_info-item')
                        .clone()
                        .removeClass('clone');

                    if (index % 2 == 1) {
                        $tr.removeClass('bg-gray-100 ')
                    }

                    $tr.find('[data-modal_info]').each((indexEl, el) => {
                        let value;
                        let keyValue = $(el).attr('data-modal_info');
                        let typeValue = $(el).attr('data-modal_info_type');
                        if (keyValue === '#') {
                            $(el).text(index + 1)
                            return;
                        }
                        try {
                            value = keyValue
                                .split('.')
                                .reduce((acc, key) => acc[key] ?? item[key], {}) ?? null;
                        } catch (error) {
                            value = null
                        }

                        if (typeValue === 'bool') {
                            if (value) {
                                $(el).html(BADGE_YN['YES'])
                            } else {
                                $(el).html(BADGE_YN['NO'])
                            }
                            return;
                        }
                        $(el).html(value ?? '<span class="text-xs text-red-300 italic">No data</span>');

                    })
                    $table.append($tr);
                });
                $MODAL_SHOW('modal_info')
            }
        }
    </script>

    <script>
        window.addEventListener("load", (event) => {
            window.DT = new DataTable('#table-data', Object.assign(DEFAULT_CONFIG_DT, {
                language: {
                    searchPlaceholder: 'keyword',
                },
                ajax: {
                    url: "{{ route('history-sn-check.get') }}",
                    data: function(d) {
                        const FROM_DATE = new DateTime('#from_date')
                        const TO_DATE = new DateTime('#to_date');

                        if (moment(FROM_DATE.val()).isValid()) {
                            const datetime = moment(FROM_DATE.val());
                            datetime.hour(0).minute(0).second(0);
                            d.from_date = moment(FROM_DATE.val()).unix();
                        }

                        if (moment(TO_DATE.val()).isValid()) {
                            const datetime = moment(TO_DATE.val());
                            datetime.hour(23).minute(59).second(59);
                            d.to_date = datetime.unix();
                        }
                    },
                },
                columnDefs: [
                    ...COLUMNS.map((column, index) => {
                        const colRender = DT_COLUMN_DEF_RENDERER({
                            column,
                            index
                        });
                        if (column['type'] == 'array') {
                            colRender['render'] = function(data, type, row) {
                                const ul = document.createElement('ul');
                                ul.style.maxWidth = '25rem'
                                ul.className = 'list-decimal'

                                data.forEach( (item, i) =>{
                                    const li = document.createElement('li');
                                    li.style.overflowX = 'auto';
                                    li.style.wordWrap = 'normal';
                                    li.style.whiteSpace = 'nowrap';
                                    li.textContent = `${i+1}. ${item}`
                                    ul.append(li)
                                });
                                return ul.outerHTML;
                            }
                        }

                        if (column['type'] == 'action') {
                            colRender['render'] = function(data, type, row) {
                                // if status not pending
                                if (row[findIndexByColumnName('status')] !== 2) {
                                    return `<button type="button" onclick="showModalInfoById(${row[findIndexByColumnName('id')]})" class="${CLASS['btn-info']}">
                                        <i class="ri-grid-line"></i>
                                    </button>`;
                                }
                                return null;
                            }
                        }

                        return colRender;
                    })
                ]
            }));

            // event
            DT.on('click', '.dt-control', function(e) {
                let tr = e.target.closest('tr');
                let row = DT.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                } else {
                    row.child(function() {
                        const $ul = $('.clone.td-control-data')
                            .clone()
                            .removeClass('clone')
                            .html('');
                        const data = row.data();
                        const values = {
                            response: data[findIndexByColumnName('response')],
                            keyword: data[findIndexByColumnName('keyword')]
                        }
                        const groupResponse = {
                            serialNumber: values.response.data.reduce((acc, item) => {
                                acc[item._serialNumber] = acc[item._serialNumber] || [];
                                acc[item._serialNumber].push(item);
                                return acc
                            }, {})
                        }
                        const founds = Object.keys(groupResponse.serialNumber);;
                        if (!founds.length) {
                            $ul.append(MSG.NOT_FOUND)
                        }
                        founds.forEach((serialNumber, index) => {
                            let $li;
                            if (values.keyword.includes(serialNumber)) {
                                $li = $('.clone.td-control-item-found')
                                    .clone()
                                    .removeClass('clone');
                                $li.find('[data-td-control="count_found"]').html(
                                    groupResponse.serialNumber[serialNumber].length)
                            } else {
                                $li = $('.clone.td-control-item-not_found')
                                    .clone()
                                    .removeClass('clone');
                                $li.find('[data-td-control="value"]').html(serialNumber)
                            }
                            $li.find('[data-td-control="value"]').html((index + 1) + '. ' +
                                serialNumber)
                            $ul.append($li);
                        });

                        return $ul;
                    }).show();
                }
            });
        })
    </script>
@endpush
