@extends('dokter.ppdsdeveloper')

@push('script')
<script type="text/javascript">
    $(function () {
        if (window.mikroExpertiseAutoOpenInitialized) {
            return;
        }
        window.mikroExpertiseAutoOpenInitialized = true;

        var focusPeriksaId = @json((string) ($focusPeriksaId ?? ''));
        var focusNoFoto = @json((string) ($focusNoFoto ?? ''));
        var returnUrl = @json($expertiseReturnUrl ?? url('/'));
        var shouldOpenOnLoad = @json((bool) ($openExpertiseOnLoad ?? false));
        var initialListMode = @json($initialListMode ?? 'searchbydate');
        var initialSearchValue = @json($initialSearchValue ?? '');
        var initialStartDate = @json($initialStartDate ?? '');
        var initialEndDate = @json($initialEndDate ?? '');
        var autoOpenAttempts = 0;
        var maxAutoOpenAttempts = 12;
        var hasOpenedTarget = false;
        var hasRequestedFilteredLoad = false;
        window.mikroExpertiseDirectOpen = shouldOpenOnLoad;
        function setInitialFilters() {
            if ($('#mulai').length) {
                $('#mulai').val(initialStartDate);
            }
            if ($('#akhir').length) {
                $('#akhir').val(initialEndDate);
            }
            if ($('#valjenis').length) {
                $('#valjenis').val(initialListMode);
            }
            if ($('#master_set01').length) {
                $('#master_set01').val(initialListMode);
            }
            if ($('#valcari').length) {
                $('#valcari').val(initialSearchValue);
            }
        }

        function findExpertiseButton(boundIndex) {
            var row = $('#gridpemeriksaan').find('[role="row"][boundindex="' + boundIndex + '"]').first();
            if (!row.length) {
                return $();
            }

            return row.find('button, input, .jqx-button').filter(function () {
                var text = $.trim($(this).text());
                var value = $.trim($(this).val());
                return text === 'Expertise' || value === 'Expertise';
            }).first();
        }

        function triggerExpertiseButton(boundIndex, rowData) {
            try {
                var columns = $('#gridpemeriksaan').jqxGrid('columns');
                var records = columns && columns.records ? columns.records : [];
                
                for (var i = 0; i < records.length; i++) {
                var column = records[i];
                if (column && typeof column.buttonclick === 'function') {
                    var renderedLabel = typeof column.cellsrenderer === 'function'
                        ? column.cellsrenderer()
                        : '';

                        if (String(renderedLabel).indexOf('Expertise') !== -1) {
                            column.buttonclick(rowData || boundIndex);
                            return true;
                        }
                    }
                }
            } catch (error) {
                console.error('[mikro-expertise] triggerExpertiseButton:error', error);
            }

            var button = findExpertiseButton(boundIndex);
            if (button.length) {
                button.trigger('click');
                return true;
            }

            return false;
        }

        function openFocusedPeriksa() {
            if (!shouldOpenOnLoad || hasOpenedTarget || !focusPeriksaId) {
                return;
            }

            var rows = $('#gridpemeriksaan').jqxGrid('getrows') || [];
            var matchedRow = null;
            var matchedRowBoundIndex = -1;

            for (var i = 0; i < rows.length; i++) {
                if (String(rows[i].id) === focusPeriksaId || (focusNoFoto !== '' && String(rows[i].nofoto) === focusNoFoto)) {
                    matchedRow = rows[i];
                    matchedRowBoundIndex = typeof rows[i].boundindex !== 'undefined'
                        ? rows[i].boundindex
                        : i;
                    break;
                }
            }

            if (!matchedRow) {
                autoOpenAttempts++;
                if (autoOpenAttempts >= maxAutoOpenAttempts) {
                    $('#divawal').show();
                } else {
                    setTimeout(openFocusedPeriksa, 500);
                }
                return;
            }

            var triggerRowIndex = matchedRowBoundIndex >= 0 ? matchedRowBoundIndex : matchedRow.boundindex;
            $('#gridpemeriksaan').jqxGrid('selectrow', triggerRowIndex);
            $('#gridpemeriksaan').jqxGrid('ensurerowvisible', triggerRowIndex);

            setTimeout(function () {
                if (triggerExpertiseButton(triggerRowIndex, matchedRow)) {
                    hasOpenedTarget = true;
                    return;
                }

                autoOpenAttempts++;
                if (autoOpenAttempts >= maxAutoOpenAttempts) {
                    $('#divawal').show();
                } else {
                    setTimeout(openFocusedPeriksa, 500);
                }
            }, 150);
        }

        function requestFilteredLoad() {
            if (hasRequestedFilteredLoad) {
                return;
            }

            hasRequestedFilteredLoad = true;
	            setInitialFilters();
	            if (typeof openedpage === 'function') {
	                openedpage();
	            } else {
	                $('#divawal').show();
	            }
	        }

	        $('#gridpemeriksaan').off('bindingcomplete.mikro-expertise').on('bindingcomplete.mikro-expertise', function () {
	            openFocusedPeriksa();
	        });

	        $(window).off('load.mikro-expertise').on('load.mikro-expertise', function () {
	            requestFilteredLoad();
	        });

	        setTimeout(function () {
	            requestFilteredLoad();
	        }, 0);

	        $('#btnkembali2').off('click.mikro-expertise').on('click.mikro-expertise', function () {
            window.location.href = returnUrl;
        });
    });
</script>
@endpush
