@extends('app')
@section('title', 'Med-X | Eligibility')

@push('styles')
    <style>
        .container {
            display: flex;
            gap: 50px;
        }
        .array-block {
            width: 100%;
            background-color: #f9f9f9;
            padding: 10px;
            border-radius: 8px;
            border: 1px solid #ddd;
            font-family: 'Courier New', Courier, monospace;
            font-size: 14px;
            overflow-x: auto;
        }
        .key {
            font-weight: bold;
        }
        ul {
            list-style-type: none;
            padding-left: 20px;
        }
        .center-box {
            max-height: 85vh;
            overflow-y: auto;
            overflow-x: hidden;
        }
        .user-list-left {
            max-height: 65vh;
        }
        /*============= 01-01-2025 ==============*/
        .eligibility-area {
            margin-bottom: 15px;
            margin-right: 0px;
        }
        .border-redius {
            border: 0px solid #1c3d6e;
            background: #f5f7f7;
            padding: 20px 30px;
            color: #1c3d6e;

        }
        .border-redius h2 {
            font-size: 20px;
            margin-bottom: 4px;
        }
        .border-redius i {
            float: left;
            font-size: 38px;
            min-height: 53px;
            /* background: #1c3d6e; */
            line-height: 53px;
            color: #1c3d6e;
            margin-right: 20px;
        }
        .plan-area {
            padding: 0px;
            margin: 10px 0;
            border: 1px solid #e8ebeb;
            background:#f5f7f7;
            font-size: 14px;
        }
        .plan-area h2 {
            font-size: 18px;
            color: #1c3d6e;
            width: 100%;
            padding: 8px 10px;
            background: #34b6b340;
        }
        .plan-area span {
            /*font-size: 16px;*/
            color: #4a4a4a;
            font-weight: 500;
        }
        .plan-area p {
            margin-bottom: 8px;
        }
        .plan-area .plan-area-detail {
            width: 100%;
            float: left;
            border-bottom: 1px solid #e8ebeb;
            margin-bottom: 8px;
            color: #4c4c4c;
        }
        .plan-area-detail.message span {
            width: 100%;
            margin-bottom: 10px;
            padding-bottom: 10px;
            font-weight: normal;
        }
        .plan-area.col-sm-4 {
            margin-left: 20px;
        }
        
            
    
        .eligibility-search-area .row {
            background: #f5f7f7;
            margin-top: 25px;
            border: 1px solid #b4b7b7;
            padding: 24px;
            margin-left: 0;
            margin-right: 15px;
        }        
        .eligibility-list-area {
            width: 100%;
            float: left;
            padding-right: 15px;
        }
        .eligibility-list-area h2 .icon {
            color: #1c3d6e;
            margin-top: 10px;
            margin-bottom: 10px;
        }
        .eligibility-list-area h2 {
            font-size: 18px;
            color: #1c3d6e;
            margin-top: 10px;
            margin-bottom: 10px;
            border-bottom:1px solid #e8ebeb;
        }
        .eligibility-list-area table thead tr th {
            font-size: 18px;
            color: #1c3d6e;
            font-weight: 500;
            padding: 8px 10px;
            background: #34b6b340;
            border: 0px;
            line-height: 1.2;
            font-size: 16px;
        }
        .eligibility-list-area table {
            border: 1px solid #e8ebeb;
        }
        .eligibility-list-area table tr td {
            border-bottom: 1px solid #e8ebeb;
            font-size: 14px;
            padding: 5px 10px;
        }
        .eligibility-list-area .group-th .bg-none {
            background: none;
        }
        .eligibility-list-area .group-th .bg-th {
            background: #f5f7f7;
        }
        .eligibility-list-area table thead tr .border-right {
            border-right: 1px solid #e8ebeb;
        }
        .eligibility-list-area table tr.border-bottom-none td {
            border-bottom: 0px;
        }
        .eligibility-list-area table tr.border-top-none td {
            border-top: 0px;
            padding-top: 0px;
        }
        .refresh {
            align-content: space-around;
            border: 1px solid #34b6b3;
            width: 40px;
            text-align: center;
            border-radius: 5px;
            height: 36px;
        }
        .toggle-btn {
            font-size: 20px;
            cursor: pointer;
            text-decoration:none;
            padding:0px;
        }
        #search-form{
            padding: 0;
        }
        #search-form label{
            font-weight: 600;
            font-size: 20px;
        }
        #search-form input {
            height: 50px;
        }
        .table-responsive {
            overflow-y: auto;   
        }
        #expandAll, #collapseAll {
            width: 125px;
        }
        #expandAll{
            margin-bottom: 10px;
        }
        .fa-shield {
            border: 0 !important;
            padding: 2px !important;
            padding-left: 2px !important;
            margin: 0 !important;
        }
        .insurance-type-1 { color: #007bff; }
        .insurance-type-2 { color: #20c997; }
        .insurance-type-3 { color: #6f42c1; }
        .insurance-type-4 { color: #28a745; }
        .insurance-type-5 { color: #fd7e14; }
        .insurance-type-6, .insurance-type-7,
        .insurance-type-8, .insurance-type-9,
        .insurance-type-10, .insurance-type-null
        { color: #dc3545; }
        .info-icon {
            position: absolute;
            right: 40px;
            cursor: pointer;
            border: 0 !important;
        }

        .info-icon .hint-box {
            display: none;
            position: absolute;
            top: 24px;
            right: 0px;
            background-color: #fff;
            border: 1px solid #ddd;
            padding: 10px 14px;
            border-radius: 6px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            width: 170px;
            font-size: 13px;
            z-index: 1000;
        }

        .info-icon:hover .hint-box {
            display: block;
        }

        .hint-item {
            display: flex;
            align-items: center;
            margin-bottom: 6px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
            font-weight: 500;
        }

        .hint-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        #nexteligibilitydates #loader{
            top: 10%;
            left: 50%;
        }
        #parse-response {
            text-decoration-line: none;
        }
        .client-message {
            font-size: 14px;
            color: gray;
            position: relative;
            vertical-align: super;
        }
        #upload-container {
            padding-right: 15px;
        }
        #uploadArea {
            border: 2px dashed #34B6B3;
            border-radius: 5px;
            padding: 15px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #history-list .pre-auth-appointment-right-list:last-child,
        #eligibility-files-list .pre-auth-appointment-file-list:last-child {
            border-bottom: none !important;
        }
    </style>
@endpush

@section('content')
    <main class="container-fluid">
        <div class="row align-items-center">
            <div class="col-sm-2">
                <div class="col-sm-12 pl-0 pr-2">
                    <a href="/dashboard">
                        <img src="{{env('AUTH_SERVER_URL')}}/public/images/MedX-Logo.png" class="pr-1" width="99%" alt="Med-X Logo">
                    </a>
                </div>
            </div>
            <div class="col-sm-10">
                <div class="mt-0 d-flex justify-content-between align-items-center">
                    <div class="d-flex">
                        <div class="dynamic-title pt-1">
                            <h4 class="secondary-color">Patient Eligibility</h4>
                        </div>
                        <div class="border-0 pl-3 pb-0">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchPatient" placeholder="Search Patient" aria-label="Search Patient">
                                <div class="input-group-append" id="search-patient">
                                    <span class="input-group-text">
                                        <i class="material-icons">search</i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <i class="ml-2 material-icons refresh">refresh</i>
                    </div>
                    <button id="syncEligibility" class="btn btn-success primary-bg-color d-none">Sync Eligibility</button>
                    <div class="border-0 pb-0 pt-1">
                        <h4 class="secondary-color mb-0">{{session('PractitionerName')}}</h4>
                        <small class="primary-color">{{session('suffix')}}</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-2">
                <div class="input-group">
                    <select class="form-control mt-3" id="searchCalander">
                        <option value="">Select Location</option>
                        @foreach($locations as $location)
                            <option value="{{$location['id']}}">{{$location['name']}}</option>
                        @endforeach
                    </select>
                </div>
                <h3 class="font-weight-light mt-3 mb-0 list-title">Scheduled Visits 
                    @if(session()->has('features') && in_array('SYNCAPPOINTMENT', session()->get('features')))
                        <i title="Sync Appointments" class="ml-2 material-icons float-right" id="sync-appointment">refresh</i>
                    @endif
                </h3>
                <div class="calendar-container d-none">
                    <i title="Previous" class="material-icons calendar-btn" id="prevBtn">navigate_before</i>
                    <!--<button class="calendar-btn" id="prevBtn"><<</button>-->
                    <span>
                        <span class="calendar-date" id="calendarDate"></span>
                        <span class="calendar-text d-none">&nbsp;(Today)</span>
                    </span>
                    <i title="Previous" class="material-icons calendar-btn" id="nextBtn">navigate_next</i>
                    <!--<button class="calendar-btn" id="nextBtn">>></button>-->
                </div>
                <div class="user-list user-list-left mt-2"><p>Please select a location to continue.</p></div>
            </div>
            <div class="col-sm-8">
                <div class="center-box mt-3">
                    <div id="eligibility-container" ><p>Please select a location and appointment to proceed.</p></div>
                </div>
                <div class="row col-md-12 eligibility-btn-panel d-none">
                    <button id="downloadPdfBtn" class="btn btn-success primary-bg-color">Download PDF</button>
                    <button id="shceduleUpload" class="btn btn-success secondary-bg-color ml-3">Resend PDF to EHR</button>
                </div>
            </div>
            <div class="col-sm-2 pl-0">
                <div class="list-group panel mt-3 history-tab d-none">
                    <a href="#history-list" id="history" class="list-group-item-history" data-toggle="collapse">
                        <span class="d-flex justify-content-between align-items-center">
                            <h3 class="font-weight-light mb-0">Eligibility History</h3>
                            <i class="fas fa-info-circle text-muted info-icon">
                                <div class="hint-box">
                                    <div class="hint-item"><span class="hint-color" style="background-color: #007bff;"></span> Primary Dental</div>
                                    <div class="hint-item"><span class="hint-color" style="background-color: #20c997;"></span> Secondary Dental</div>
                                    <div class="hint-item"><span class="hint-color" style="background-color: #6f42c1;"></span> Tertiary Dental</div>
                                    <div class="hint-item"><span class="hint-color" style="background-color: #28a745;"></span> Primary Medical</div>
                                    <div class="hint-item"><span class="hint-color" style="background-color: #fd7e14;"></span> Secondary Medical</div>
                                    <div class="hint-item"><span class="hint-color" style="background-color: #dc3545;"></span> Other</div>
                                </div>
                            </i>
                            <i class="fas fa-angle-up"></i>
                        </span>
                    </a>
                    <div class="d-grid pt-2 collapse show" id="history-list"><p>Please select an location and appointment to proceed.</p></div>
                    <hr/>
                    <a href="#eligibility-files-list" id="eligibility" class="list-group-item-eligibility" data-toggle="collapse">
                        <span class="d-flex justify-content-between align-items-center">
                            <h3 class="font-weight-light mb-0">Uploaded Eligibility</h3>
                            <i class="fas fa-angle-down"></i>
                        </span>
                    </a>
                    <div class="d-grid pt-2 collapse" id="eligibility-files-list"><p>No files have been uploaded yet.</p></div>
                </div>
                <!-- <h3 class="font-weight-light mt-3 mb-0">Eligibility History</h3>
                <i class="fas fa-info-circle text-muted info-icon">
                    <div class="hint-box">
                        <div class="hint-item"><span class="hint-color" style="background-color: #007bff;"></span> Primary Dental</div>
                        <div class="hint-item"><span class="hint-color" style="background-color: #20c997;"></span> Secondary Dental</div>
                        <div class="hint-item"><span class="hint-color" style="background-color: #6f42c1;"></span> Tertiary Dental</div>
                        <div class="hint-item"><span class="hint-color" style="background-color: #28a745;"></span> Primary Medical</div>
                        <div class="hint-item"><span class="hint-color" style="background-color: #fd7e14;"></span> Secondary Medical</div>
                        <div class="hint-item"><span class="hint-color" style="background-color: #dc3545;"></span> Other</div>
                    </div>
                </i>
                <div class="mt-2 pr-1">
                    <div class="pt-1 pr-3" id="history-list"><p>Please select an appointment to proceed.</p></div>
                </div> -->
            </div>
        </div>
        <!-- Eligibility Modal -->
        <div class="modal" id="eligibilityFile" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <i class="material-icons-outlined eligibility-modal-close close-icon-btn" data-dismiss="modal">close</i>
                    <div class="modal-body eligibilityFile-data">
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-danger eligibility-modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Help Modal -->
        <div class="modal" id="helpModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <i class="material-icons" data-dismiss="modal">arrow_back</i>
                        <h5 class="modal-title">
                            Help Documentation
                        </h5>
                        <span class="web-version">V - 1.6</span>
                    </div>
                    <div class="modal-body help-body">
                    </div>
                </div>
            </div>
        </div>
    </main>
@endsection

@push('scripts')
    <script>
        let searchTables = [];
        $(document).ready(function() {
            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

            function formatDateTime(dateString, options = {}) {
                const dateObj = new Date(dateString);
                if (isNaN(dateObj.getTime())) return null;
                const { format = 'date', locale = 'en-US', includeTime = false, hour12 = true } = options;
                let formattedDate = '';
                switch (format) {
                    case 'hm12':
                        formattedDate = dateObj.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12 });
                        break;
                    case 'MsD2Yn':
                        formattedDate = dateObj.toLocaleDateString(locale, { month: 'short', day: '2-digit', year: 'numeric' });
                        break;
                    case 'M2D2Yn':
                        formattedDate = dateObj.toLocaleDateString(locale, {month: "2-digit", day: "2-digit", year: "numeric"});
                        break;
                    case 'YnMsD2':
                        formattedDate = dateObj.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: '2-digit' });
                        break;
                    case 'dateNumeric':
                        formattedDate = dateObj.toLocaleDateString(locale, { year: 'numeric', month: '2-digit', day: '2-digit' });
                        break;
                    case 'full':
                        formattedDate = dateObj.toLocaleString(locale, { month: 'short', day: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', hour12, timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone });
                        break;
                    default:
                        formattedDate = dateObj.toISOString();
                        break;
                }
                return formattedDate;
            }
            
            const costomTimeZone = timeZone;
            // Function to format the date
            function formatDate(date) {
                const options = { year: 'numeric', month: 'short', day: '2-digit', timeZone: costomTimeZone };
                return new Intl.DateTimeFormat('en-US', options).format(date);
            }
            // Get current date in costomTimeZone
            function getCurrentDate() {
                const now = new Date();
                return new Date(now.toLocaleString("en-US", { timeZone: costomTimeZone }));
            }
            const normalizeDate = date => {
                const d = new Date(date);
                d.setHours(0, 0, 0, 0);
                return d;
            };
            let currentDate = getCurrentDate();
            // Update calendar date
            function updateCalendar() {
                jQuery('.calendar-text').addClass('d-none');
                if(normalizeDate(getCurrentDate()).getTime() === normalizeDate(currentDate).getTime()){
                    jQuery('.calendar-text').removeClass('d-none');
                }
                $('#calendarDate').text(formatDate(currentDate));
                if(jQuery('#searchCalander').val() != ''){
                    getAppointmentsList(jQuery('#searchCalander').val());
                }else{
                    jQuery('.user-list-left').html('<p>Please select a location to continue.</p>');
                }
            }
            // Previous month
            $('#prevBtn').click(function() {
                currentDate.setDate(currentDate.getDate() - 1);
                updateCalendar();
            });
            // Next month
            $('#nextBtn').click(function() {
                currentDate.setDate(currentDate.getDate() + 1);
                updateCalendar();
            });
            updateCalendar();
            
            var appointmentsData = [];
            function displayAppointments(scheduledAppointments) {
                jQuery('.history-tab').addClass('d-none');
                const userList = $('.user-list-left');
                userList.empty();
                const currentTime = new Date();
                if(scheduledAppointments.length > 0) {
                    scheduledAppointments.forEach(item => {
                        const itemTimeSlot = new Date(item.timeSlot);
                        const appointmentTime = formatDateTime(item.timeSlot, {format:'hm12',  locale:'en-US', hour12:true});
                        let timeDiff = itemTimeSlot - currentTime;
                        let dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)) + 1;
                        // const appointmentTime = new Date(item.timeSlot).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        const appointmentId = item.appointmentId;
                        const appointmentStatus = item.appointmentStatus;
                        const patientId = item.patientURL;
                        const external_patient_id = item.external_patient_id;
                        const appointmentType = item.appointmentType;
                        const patientName = `${item.patientPrefix} ${item.patient}`;
                        
                        const userItem = `
                            <div class="user-item-left pre-auth-appointment-list ${appointmentStatus}" data-appointmentId="${appointmentId}" data-patientId="${patientId}" data-external_patient_id="${external_patient_id}" data-patientName="${patientName}">
                                <h5>${patientName}</h5>
                                <small>${appointmentTime} | ${appointmentType}</small>
                            </div>
                        `;
                        
                        userList.append(userItem);
                    });
                } else {
                    userList.append('<p>You don\'t have any scheduled appointments.</p>');
                }
            }
            
            function getAppointmentsList(locationId) {
                jQuery('.history-tab').addClass('d-none');
                jQuery('#syncEligibility').addClass('d-none');
                const formData = new FormData();
                formData.append('practitioner', "{{ session('GHAccessToken') ?? session('accessToken') }}");
                formData.append('locationId', locationId);
                formData.append('timezone', timeZone);
                formData.append('date', $('#calendarDate').text());
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/get-appointments",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.user-list-left').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('#history-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-files-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-container').html('<p>Please select an appointment to proceed.</p>');
                $.ajax(settings).done(response => {
                    if(response.data && response.data.length > 0){
                        appointmentsData = response.data;
                        displayAppointments(response.data);
                    }else{
                        jQuery('.user-list-left').html('<p>You don\'t have any scheduled appointments.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error while fetching patients list. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            jQuery('.refresh').click(function() {
                jQuery('.calendar-container').addClass('d-none');
                currentDate = getCurrentDate();
                $('#calendarDate').text(formatDate(currentDate));
                jQuery('#searchCalander').val('');
                jQuery('#searchPatient').val('');
                jQuery('.list-title').html('Scheduled Visits');
                jQuery('#searchCalander').removeClass('d-none');
                jQuery('#syncEligibility').addClass('d-none');
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('.user-list-left').html('<p>Please select a location to continue.</p>');
                jQuery('#history-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-files-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-container').html('<p>Please select an appointment to proceed.</p>');
                jQuery('.history-tab').addClass('d-none');
            });
            
            jQuery(document).on('change', '#searchCalander', function() {
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('.history-tab').addClass('d-none');
                jQuery('#syncEligibility').addClass('d-none');
                jQuery('.calendar-container').removeClass('d-none');
                if(jQuery(this).val() != ''){
                    getAppointmentsList(jQuery(this).val());
                }
                else{
                    jQuery('.calendar-container').addClass('d-none');
                    currentDate = getCurrentDate();
                    $('#calendarDate').text(formatDate(currentDate));
                    Swal.fire({
                        position: "top-end",
                        text: 'Please change the location to get appointments.',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    jQuery('.user-list-left').html('<p>Appointments not found for selected location.</p>');
                }
            });

            jQuery(document).on('click', '#sync-appointment', function() {
                jQuery('#sync-appointment').addClass('syncdisable');
                jQuery('.history-tab').addClass('d-none');
                jQuery('.calendar-container').addClass('d-none');
                jQuery('#syncEligibility').addClass('d-none');
                currentDate = getCurrentDate();
                $('#calendarDate').text(formatDate(currentDate));
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('#searchCalander').val('');
                jQuery('#searchPatient').val('');
                const formData = new FormData();
                formData.append('practitioner', "{{ session('GHAccessToken') ?? session('accessToken') }}");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/sync-appointment",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.user-list-left').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                jQuery('#history-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-files-list').html('<p>Please select a location and appointment to proceed.</p>');
                jQuery('#eligibility-container').html('<p>Please select an appointment to proceed.</p>');
                $.ajax(settings).done(response => {
                    Swal.fire({
                        position: "top-end",
                        text: response.message,
                        showConfirmButton: false,
                        timer: 2000
                    });
                    jQuery('.user-list-left').html('<p>Please select a location to continue.</p>');
                    jQuery('#sync-appointment').removeClass('syncdisable');
                    // getAppointmentsList();
                }).fail((jqXHR, textStatus, errorThrown) => {
                    // getAppointmentsList();
                    jQuery('#sync-appointment').removeClass('syncdisable');
                    jQuery('.user-list-left').html('<p>Please select a location to continue.</p>');
                    // jQuery('.user-list-left').html('<p>Error while fetching patients list. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            function eligibilityPullDataDisplay(lastpulls) {
                const historyList = $('#history-list');
                historyList.empty();
                $.each(lastpulls, function(index, lastpull) {
                    const lastPullTime = formatDateTime(lastpull.created_at, {format:'full',  locale:'en-US', hour12:true});
                    $('#history-list').append(`
                        <div title="${lastpull.ins_carrier}" class="right-bottom-border pre-auth-appointment-right-list ${index == 0 ? 'pre-auth-appointment-right-list-selected' : ''}" 
                            data-patientid="${lastpull.patient_id}"
                            data-external_appointment_id="${lastpull.appointment_id}"
                            data-external_patient_id="${lastpull.external_patient_id}"
                            data-created_at="${lastpull.created_at}"
                            data-uuid="${lastpull.uuid}"
                            data-is_manual_upload_required="${lastpull.is_manual_upload_required}"
                            data-is_retryable="${lastpull.is_retryable}"
                            data-is_uploaded="${lastpull.is_uploaded}"
                            data-eligibility_file="${lastpull.eligibility_file}">
                            <span id="appointment" class="m-0">
                                <i class="fas fa-shield insurance-type-${lastpull.sequence_code}"></i>
                                <span>${lastPullTime}</span>
                            </span>
                        </div>
                    `);
                });
            }
            
            const maxLength = 100;
            $(document).on('click', '.toggle-read-more', function (e) {
                e.preventDefault();
                const fullText = $(this).attr('data-full-text');
                const isShort = jQuery('.read-more').text().includes("...");
                if (isShort) {
                    jQuery('.read-more').text(fullText);
                    $(this).text('Read Less');
                } else {
                    const shortText = fullText.substring(0, maxLength) + '...';
                    jQuery('.read-more').text(shortText);
                    $(this).text('Read More');
                }
            });
            
            // Function to handle nested arrays/objects and format them as lists
            function formatCell(cellValue) {
                if (Array.isArray(cellValue)) {
                    return `<ul class="pl-0">${cellValue.map(item => `<li>${formatCell(item)}</li>`).join('')}</ul>`;
                } else if (typeof cellValue === "object" && cellValue !== null) {
                    return `<ul class="pl-0">${Object.entries(cellValue).map(([key, val]) => 
                        `<li><strong class="text-capitalize">${key.replace(/([A-Z])/g, ' $1').trim()}:</strong> ${val ?? '-'}</li>`
                    ).join('')}</ul>`;
                }
                return cellValue ?? "No Data";
            }
            
            function displayEligibilityData(getResponse, responseParse, error) {
                let parentElement = '#eligibility-container';
                let content = '';
                let responseParseHtml = '';
                let added = false;
                let excludeKeys = ["subscriber", "status", "patient", "planBenefits", "activeCoverage", "payer"];
                searchTables = [];
                if(getResponse.length == 0 && responseParse.length == 0){
                    var errorHtml = '';
                    errorHtml += `<div class=" eligibility-search-area">
                                    <div class="row">
                                        <ul id="errorList" class="mb-0 pl-0">
                                            <li>
                                                <b>Name: </b>
                                                ${$(".user-item-left.pre-auth-appointment-list-selected").attr("data-patientname")} (${$(".user-item-left.pre-auth-appointment-list-selected").attr("data-carestackpatientid")})
                                                <hr class="mt-1 mb-1">
                                            </li>`;
                                            if (error.status && error.status.description) {
                                                errorHtml += `<li>
                                                    <b>Status:</b>
                                                    <ul class="mb-0">
                                                      <li><b>Code: </b>${error.status.code}</li>
                                                      <li><b>Description: </b>${error.status.description}</li>
                                                    </ul>
                                                  </li>`;
                                            }
                                            if (Array.isArray(error.messages) && error.messages.length > 0) {
                                                errorHtml += `<li>
                                                    <b>Messages:</b>
                                                    <ul class="mb-0">`;
                                                        error.messages.forEach(msg => {
                                                            errorHtml += `<li>${msg}</li>`;
                                                        });
                                                    errorHtml += `<ul>
                                                </li>`;
                                            }
                    errorHtml +=        `</ul>
                                    </div>
                                </div>`;
                    $(parentElement).html(errorHtml);
                    return;
                }
                // Active Coverage
                if (getResponse.subscriber) {
                    const subscriberData = getResponse.subscriber;
                    content +=`<div class="eligibility-area row">
                        <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">how_to_reg</i>
                                <h2>${getResponse.status && getResponse.status != "" ? getResponse.status : "-"}</h2>
                                <span>Coverage Status</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">medical_services</i>
                                <h2>${subscriberData.plan.subscriberId && subscriberData.plan.subscriberId != "" ? subscriberData.plan.subscriberId : '-'}</h2>
                                <span>Subscriber ID</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                               <i class="material-icons-outlined">confirmation_number</i>
                                <h2>${subscriberData.plan.groupNumber && subscriberData.plan.groupNumber != "" ? subscriberData.plan.groupNumber : '-'}</h2>
                                <span>Group Number</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">date_range</i>
                                <h2>${subscriberData.plan.effectiveDateFrom && subscriberData.plan.effectiveDateFrom != '' ?  subscriberData.plan.effectiveDateFrom : '-'}</h2>
                                <span>Effective Date From</span>
                            </div>
                        </div>
                    </div>`;
                }    
                    
                if (getResponse.subscriber || getResponse.patient) {
                    content += `<div class="row " style="margin-right:0;">`;
                        if (getResponse.subscriber) {
                            content += `<div class="col-sm-8">
                                            <div class="plan-area fa-pull-left">
                                                <h2>Plan Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Member Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.firstName} ${getResponse.subscriber.lastName}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Member Address</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.address ? Object.values(getResponse.subscriber.address).filter(value => value !== "").join(", ") : '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Date Of Birth</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.dateOfBirth}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Group Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.groupName ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Plan Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.planName ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Plan Number</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.planNumber ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Coverage Indicator</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.coverageIndicator ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Service Types</p>
                                                        <span class="fa-pull-right">${getResponse.planBenefits.serviceTypes.join(', ') ?? '-'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>`;
                        }
                        if (getResponse.patient) {
                            content += `<div class="col-sm-4">
                                            <div class="plan-area fa-pull-left mb-3 pb-1">
                                                <h2>Patient Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Full Name</p>
                                                        <span class="fa-pull-right">${getResponse.patient.firstName} ${getResponse.patient.lastName}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Address</p>
                                                        <span class="fa-pull-right">${getResponse.patient.address ? Object.values(getResponse.patient.address).filter(value => value !== "").join(", ") : '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Date Of Birth</p>
                                                        <span class="fa-pull-right">${getResponse.patient.dateOfBirth}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Relationship</p>
                                                        <span class="fa-pull-right">${getResponse.patient.relationship}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="plan-area fa-pull-left w-100">
                                                <h2>Payer Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Payer Id</p>
                                                        <span class="fa-pull-right">${getResponse.payer.id}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Payer Name</p>
                                                        <span class="fa-pull-right">${getResponse.payer.name}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>`;
                        }
                    content += `</div>`;
                }

                content += `<div id="upload-container" class="mt-4">
                        <div class="upload-area" id="uploadArea">
                            <i class="fas fa-cloud-upload-alt pr-3"></i>
                            <p>Select an eligibility file to upload (PDF format only, up to 32 MB).</p>
                            <input type="file" id="fileInput" name="files">
                        </div>
                    </div>`;
                $(parentElement).append(content);

                if(getResponse.errors){
                    var errorHtml = '';
                    var isManualUploadRequired = jQuery('.pre-auth-appointment-right-list-selected').attr('data-is_manual_upload_required');
                    var isUploaded = jQuery('.pre-auth-appointment-right-list-selected').attr('data-is_uploaded');
                    errorHtml += `<div class=" eligibility-search-area">
                                    <div class="row">
                                        <ul id="errorList" class="mb-0 pl-0">`;
                                            $.each(getResponse.errors, function(index, error) {
                                                errorHtml += `<li>${error.errorMessage}</li>`;
                                            });
                    errorHtml +=          `</ul>
                                    </div>
                                </div>`;
                    /*if(isManualUploadRequired == 'true' && isUploaded == 'false') {
                        errorHtml += `<div id="upload-container" class="mt-4">
                            <div class="upload-area" id="uploadArea">
                                <i class="fas fa-cloud-upload-alt pr-3"></i>
                                <p>Select an eligibility file to upload (PDF format only, up to 32 MB).</p>
                                <input type="file" id="fileInput" name="files">
                            </div>
                        </div>`;
                    }*/
                    $(parentElement).append(errorHtml);
                }else{
                    var search = `<div class=" eligibility-search-area">
                                <div class="row" style="">
                                    <div class="col-sm-10 pl-0 d-inline-flex align-items-center">
                                        <div id="search-form" class="col-sm-9 d-flex align-items-center">
                                            <label class="form-label mb-0 pr-2">Search Eligibility:</label>
                                            <input type="text" id="EligibilityFilterBox" class="form-control col-sm-7" placeholder="Type Code or Service etc" onkeyup="filterEligibility('EligibilityFilterBox')">
                                        </div>
                                        <div class="d-grid">
                                            <label class="mb-0" style="height: 30px;">
                                                <input type="checkbox" id="inNetworkCheckbox" onchange="filterEligibility('EligibilityFilterBox')"> In-Network
                                                </label>
                                            <label class="mb-0" style="height: 20px;">
                                                <input type="checkbox" id="outNetworkCheckbox" onchange="filterEligibility('EligibilityFilterBox')"> Out-Of-Network
                                                </label>
                                            </div>
                                    </div>
                                    <div class="col-sm-2 p-0 d-grid" style="
                                ">
                                        <button id="expandAll" class="btn btn-primary primary-bg-color mr-3">Expand All</button>
                                        <button id="collapseAll" class="btn btn-secondary secondary-bg-color">Collapse All</button>
                                    </div>
                                </div>
                            </div>`;

                    $.each(getResponse, function (key, value) {
                        if (excludeKeys.includes(key)) return;
                
                        let tableId = "table_" + key;
                        searchTables.push(tableId + 's');
                        let sectionTitle = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
                
                        let tableHtml = `
                            <div class="eligibility-list-area">
                                <h2 class="d-flex justify-content-between align-items-center">
                                    ${sectionTitle}
                                    <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#${tableId}" aria-expanded="false">
                                        <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                    </button>
                                </h2>
                                <div class="collapse" id="${tableId}">
                                    <div class="table-responsive line-items">
                                        <table class="table w-100 p-0" id="${tableId}s">
                                            <thead><tr id="${tableId}_head"></tr></thead>
                                            <tbody id="${tableId}_body"></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>`;

                        if(!added){
                            $(parentElement).append(search);
                            added = true;
                        }
                        $(parentElement).append(tableHtml);
                
                        let tableHead = $(`#${tableId}_head`);
                        let tableBody = $(`#${tableId}_body`);
                        let headers = new Set();
                
                        // Step 1: Collect all unique headers from all records
                        if (Array.isArray(value) && value.length > 0) {
                            value.forEach(row => {
                                Object.keys(row).forEach(header => headers.add(header));
                            });
                        } else if (typeof value === "object" && value !== null) {
                            Object.keys(value).forEach(header => headers.add(header));
                        }
                
                        headers = Array.from(headers); // Convert Set to Array for consistent ordering
                
                        // Step 2: Generate headers dynamically
                        headers.forEach(header => {
                            tableHead.append(`<th>${header.replace(/([A-Z])/g, " $1").replace(/^./, str => str.toUpperCase()).trim()}</th>`);
                        });
                
                        // Step 3: Populate table rows
                        if (Array.isArray(value) && value.length > 0) {
                            value.forEach(row => {
                                let rowHtml = "<tr>";
                                headers.forEach(header => {
                                    rowHtml += `<td>${formatCell(row[header] ?? "No Data")}</td>`;
                                });
                                rowHtml += "</tr>";
                                tableBody.append(rowHtml);
                            });
                        } else if (typeof value === "object" && value !== null) {
                            let rowHtml = "<tr>";
                            headers.forEach(header => {
                                rowHtml += `<td>${formatCell(value[header] ?? "No Data")}</td>`;
                            });
                            rowHtml += "</tr>";
                            tableBody.append(rowHtml);
                        }
                    });
                    
                    if(responseParse != null && typeof responseParse == "object" && Array.isArray(responseParse) && responseParse.length > 0){
                        responseParseHtml += `<div class="eligibility-list-area">
                                        <!--<div class="d-flex justify-content-between align-items-center"></div>-->
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Next Eligible Dates
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#CDTCodeTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="CDTCodeTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="CDTCodesTable">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Code</th>
                                                            <th scope="col">Last Service Date</th>
                                                            <th scope="col">Next Eligible Service Date</th>
                                                            <th scope="col">Authorization Required</th>
                                                            <th scope="col">Quick Notes</th>
                                                            <th scope="col">Coverage %</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        responseParse.forEach(parse => {
                                                            responseParseHtml += `<tr>
                                                                <td scope="col">${parse["Code"] ?? '-'}</td>
                                                                <td scope="col">${parse["Lastservicedate"]}</td>
                                                                <td scope="col">${parse["Nexteligibleservicedate"]}</td>
                                                                <td scope="col">${parse["Authorizationrequired"]}</td>
                                                                <td scope="col">${parse["Quicknotes"] ?? '-'}</td>
                                                                <td scope="col">${parse["Coverage%"]}</td>
                                                            </tr>`;
                                                        });
                                        responseParseHtml += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }else{
                        responseParseHtml += `<div class="eligibility-list-area">
                                <h2 class="d-flex justify-content-between align-items-center">Next Eligible Dates
                                    <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#CDTCodeTable" id="parse-response" aria-expanded="false">
                                        <span class="client-message">Click here to get next eligible date</span>
                                        <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                    </button>
                                </h2>
                                <div class="collapse" id="CDTCodeTable">
                                    <div class="table-responsive line-items">
                                        <table class="table w-100 p-0" id="CDTCodeTables">
                                            <thead>
                                                <tr>
                                                    <th scope="col">Code</th>
                                                    <th scope="col">Last Service Date</th>
                                                    <th scope="col">Next Eligible Service Date</th>
                                                    <th scope="col">Authorization Required</th>
                                                    <th scope="col">Quick Notes</th>
                                                    <th scope="col">Coverage %</th>
                                                </tr>
                                            </thead>
                                            <tbody id="nexteligibilitydates">
                                                <tr>
                                                    <td colspan="6">
                                                        <div class="loader-container">
                                                            <div class="loader" id="loader"></div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>`;
                    }
                    $(parentElement).append(responseParseHtml);
                }
            }

            function displayEligibilityDataOLD(getResponse, responseParse){
                let content = '';
                // Active Coverage
                if (getResponse.subscriber) {
                    const subscriberData = getResponse.subscriber;
                    content +=`<div class="eligibility-area row">
                        <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">how_to_reg</i>
                                <h2>${getResponse.status && getResponse.status != "" ? getResponse.status : "-"}</h2>
                                <span>Coverage Status</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">medical_services</i>
                                <h2>${subscriberData.plan.subscriberId && subscriberData.plan.subscriberId != "" ? subscriberData.plan.subscriberId : '-'}</h2>
                                <span>Subscriber ID</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                               <i class="material-icons-outlined">confirmation_number</i>
                                <h2>${subscriberData.plan.groupNumber && subscriberData.plan.groupNumber != "" ? subscriberData.plan.groupNumber : '-'}</h2>
                                <span>Group Number</span>
                            </div>
                        </div>
                         <div class="col-sm-3">
                            <div class="border-redius">
                                <i class="material-icons-outlined">date_range</i>
                                <h2>${subscriberData.plan.effectiveDateFrom && subscriberData.plan.effectiveDateFrom != '' ?  subscriberData.plan.effectiveDateFrom : '-'}</h2>
                                <span>Effective Date From</span>
                            </div>
                        </div>
                    </div>`;
                }    
                    
                if (getResponse.subscriber || getResponse.patient) {
                    content += `<div class="row " style="margin-right:0;">`;
                        if (getResponse.subscriber) {
                            content += `<div class="col-sm-8">
                                            <div class="plan-area fa-pull-left">
                                                <h2>Plan Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Member Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.firstName} ${getResponse.subscriber.lastName}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Member Address</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.address ? Object.values(getResponse.subscriber.address).filter(value => value !== "").join(", ") : '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Date Of Birth</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.dateOfBirth}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Group Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.groupName ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Plan Name</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.planName ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Plan Number</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.planNumber ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Coverage Indicator</p>
                                                        <span class="fa-pull-right">${getResponse.subscriber.plan.coverageIndicator ?? '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Service Types</p>
                                                        <span class="fa-pull-right">${getResponse.planBenefits.serviceTypes.join(', ') ?? '-'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>`;
                        }
                        if (getResponse.patient) {
                            content += `<div class="col-sm-4">
                                            <div class="plan-area fa-pull-left mb-3 pb-1">
                                                <h2>Patient Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Full Name</p>
                                                        <span class="fa-pull-right">${getResponse.patient.firstName} ${getResponse.patient.lastName}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Address</p>
                                                        <span class="fa-pull-right">${getResponse.patient.address ? Object.values(getResponse.patient.address).filter(value => value !== "").join(", ") : '-'}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Date Of Birth</p>
                                                        <span class="fa-pull-right">${getResponse.patient.dateOfBirth}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Relationship</p>
                                                        <span class="fa-pull-right">${getResponse.patient.relationship}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="plan-area fa-pull-left w-100">
                                                <h2>Payer Detail</h2>
                                                <div class="col-sm-12">
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Payer Id</p>
                                                        <span class="fa-pull-right">${getResponse.payer.id}</span>
                                                    </div>
                                                    <div class="plan-area-detail" >
                                                        <p class="fa-pull-left">Payer Name</p>
                                                        <span class="fa-pull-right">${getResponse.payer.name}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>`;
                        }
                    content += `</div>`;
                }
                
                if(getResponse.errors){
                    content += `<div class=" eligibility-search-area">
                                    <div class="row">
                                        <ul id="errorList" class="mb-0 pl-0">`;
                                            $.each(getResponse.errors, function(index, error) {
                                                content += `<li>${error.errorMessage}</li>`;
                                            });
                    content +=          `</ul>
                                    </div>
                                </div>`;
                }else{
                    content += `<div class=" eligibility-search-area">
                                    <div class="row ">
                                        <div id="search-form" class="col-sm-8 d-flex align-items-center">
                                            <label class="form-label mb-0 pr-2">Search Eligibility:</label>
                                            <input type="text" id="EligibilityFilterBox" class="form-control col-sm-7" placeholder="Type Code or Service etc" onkeyup="filterEligibility('EligibilityFilterBox')">
                                        </div>
                                        <div class="col-sm-4 d-flex p-0 justify-content-end">
                                            <button id="expandAll" class="btn btn-primary primary-bg-color mr-3">Expand All</button>
                                            <button id="collapseAll" class="btn btn-secondary secondary-bg-color">Collapse All</button>
                                        </div>
                                    </div>
                                </div>`;
                    // Limitation and Maximum
                    if (getResponse.limitationAndMaximum) {
                        var groupedData = {};
                        getResponse.limitationAndMaximum.filter(entry => entry.hasOwnProperty('amount')).forEach(entry => {
                                var network = entry.network;
                                var planCoverage = entry.planCoverageDescription;
                                var message = entry.message;
                                if (!groupedData[network]) {
                                    groupedData[network] = {};
                                }
                                if (!groupedData[network][planCoverage]) {
                                    groupedData[network][planCoverage] = {
                                        'Benefit Maximum': '',
                                        'Benefit Remaining': '',
                                        'Network': network
                                    };
                                }
                                if (message === "Benefit Maximum") {
                                    groupedData[network][planCoverage]['Benefit Maximum'] = entry.amount ? '$'+Math.round(entry.amount) : '-';
                                } else if (message === "Benefit Remaining") {
                                    groupedData[network][planCoverage]['Benefit Remaining'] = entry.amount ? '$'+Math.round(entry.amount) : '-';
                                }
                            });
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Benefit Max & Remaining
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#benefitTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="benefitTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="benefitsTable">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Plan Coverage Description</th>
                                                            <th scope="col">Network</th>
                                                            <th scope="col">Benefit Maximum</th>
                                                            <th scope="col">Benefit Remaining</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        $.each(groupedData, function (network, plans) {
                                                            $.each(plans, function (planCoverage, values) {
                                                                content += `<tr>
                                                                    <td>${planCoverage}</td>
                                                                    <td>${values['Network']}</td>
                                                                    <td>${values['Benefit Maximum']}</td>
                                                                    <td>${values['Benefit Remaining']}</td>
                                                                </tr>`;
                                                            });
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }

                    // Deductible
                    if (getResponse.deductible) {
                        var groupedData = [];
                        $.each(getResponse.deductible, function (index, item) {
                            var existing = groupedData.find(row => 
                                row.network === item.network && 
                                row.insuranceType === item.insuranceType &&
                                row.planCoverageDescription === item.planCoverageDescription
                            );
                            if (!existing) {
                                groupedData.push({
                                    network: item.network,
                                    insuranceType: item.insuranceType,
                                    planCoverageDescription: item.planCoverageDescription,
                                    Individual: { amount: "-", remaining: "-" },
                                    Family: { amount: "-", remaining: "-" }
                                });
                                existing = groupedData[groupedData.length - 1];
                            }
                            if (item.planPeriod === "Remaining") {
                                existing[item.coverageLevel].remaining = item.amount;
                            } else {
                                existing[item.coverageLevel].amount = item.amount || 0;
                            }
                        });
                        
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Deductible
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#DeductibleTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="DeductibleTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="DeductTable">
                                                    <thead>
                                                        <tr class="group-th">
                                                            <th scope="col" colspan="3" class="bg-none border-right"></th>
                                                            <th scope="col" class="text-center bg-th border-right" colspan="2">Individual</th>
                                                            <th scope="col" class="text-center bg-th" colspan="2">Family</th>
                                                        </tr>
                                                        <tr>
                                                            <th scope="col">Network</th>
                                                            <th scope="col" width="230px">Insurance Type</th>
                                                            <th scope="col" class="border-right">Plan Coverage</th>
                                                            <th scope="col" class="text-center">Amount</th>
                                                            <th scope="col" class="text-center">Remaining</th>
                                                            <th scope="col" class="text-center">Amount</th>
                                                            <th scope="col" class="text-center">Remaining</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        $.each(groupedData, function (index, deduct) {
                                                            content += `<tr>
                                                                        <td scope="col">${deduct.network}</td>
                                                                        <td scope="col">${deduct.insuranceType}</td>
                                                                        <td scope="col">${deduct.planCoverageDescription || '-'}</td>
                                                                        <td scope="col">${`$${Math.round(deduct.Individual.amount)}`|| '-'}</td>
                                                                        <td scope="col">${`$${Math.round(deduct.Individual.remaining)}`|| '-'}</td>
                                                                        <td scope="col">${`$${Math.round(deduct.Family.amount)}`|| '-'}</td>
                                                                        <td scope="col">${`$${Math.round(deduct.Family.remaining)}`|| '-'}</td>
                                                                     </tr>`;
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }
                    
                    if (typeof getResponse !== 'undefined' && getResponse.coInsurance) {
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Co-Insurance
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#CoInsuranceTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="CoInsuranceTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="CoInsTable">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Insurance Type</th>
                                                            <th scope="col">Network</th>
                                                            <th scope="col">Plan Coverage Description</th>
                                                            <th scope="col">Percent</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        getResponse.coInsurance.forEach(coinsure => {
                                                            content += `<tr>
                                                                <td scope="col">${coinsure.insuranceType || '-'}</td>
                                                                <td scope="col">${coinsure.network || '-'}</td>
                                                                <td scope="col">${coinsure.planCoverageDescription || '-'}</td>
                                                                <td scope="col">${coinsure.percent}%</td>
                                                            </tr>`;
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }
                    
                    // Limitation and Maximum
                    if (getResponse.limitationAndMaximum) {
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Maximums
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#MaximumsTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="MaximumsTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="MaximumTable">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Code</th>
                                                            <th scope="col">Network</th>
                                                            <th scope="col">Insurance Type</th>
                                                            <th scope="col">Limitation</th>
                                                            <th scope="col">Service Dates</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        getResponse.limitationAndMaximum.filter(maximum => !maximum.hasOwnProperty('amount')).forEach(maximum => {
                                                            let border = '';
                                                            if(maximum.message){ border = 'border-bottom-none'; }
                                                            content += `<tr class="${border}">
                                                                <td>${maximum.code || "-"} <span style="position: absolute; width: 0; height: 0; overflow: hidden;">${maximum.message}</span></td>
                                                                <td>${maximum.network || "-"}</td>
                                                                <td>${maximum.insuranceType || "-"}</td>
                                                                <td>${maximum.limitation && Array.isArray(maximum.limitation) ? maximum.limitation.join("<br>") : "-"}</td>
                                                                <td>${maximum.serviceDates && Array.isArray(maximum.serviceDates) ? maximum.serviceDates.join("<br>") : "-"}</td>
                                                            </tr>`;
                                                            if(maximum.message){
                                                                content += `<tr class="border-top-none">
                                                                    <td scope="col" colspan="5"><b>Message: </b>${maximum.message}</td>
                                                                </tr>`;
                                                            }
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }
        
                    if (typeof getResponse !== 'undefined' && getResponse.notCovered) {
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Not Covered
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#NotCoveredTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="NotCoveredTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="NotCovered">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Code</th>
                                                            <th scope="col">Insurance Type</th>
                                                            <th scope="col">Network</th>
                                                            <th scope="col">Message</th>
                                                            <th scope="col">Service Dates</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        getResponse.notCovered.forEach(notcovered => {
                                                            content += `<tr>
                                                                <td scope="col">${notcovered.code || '-'}</td>
                                                                <td scope="col">${notcovered.insuranceType || '-'}</td>
                                                                <td scope="col">${notcovered.network || '-'}</td>
                                                                <td scope="col">${notcovered.message || '-'}</td>
                                                                <td scope="col">${notcovered.serviceDates && Array.isArray(notcovered.serviceDates) ? notcovered.serviceDates.join("<br>") : "-"}</td>
                                                            </tr>`;
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }
                    
                    if (typeof getResponse !== 'undefined' && getResponse.otherBenefit) {
                        content += `<div class="eligibility-list-area">
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Other Benefit
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#OtherBenefitTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="OtherBenefitTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="OtherBenefit">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Code</th>
                                                            <th scope="col">Insurance Type</th>
                                                            <th scope="col">Plan Coverage Description</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        getResponse.otherBenefit.forEach(otherbenefit => {
                                                            content += `<tr>
                                                                <td scope="col">${otherbenefit.code || '-'}</td>
                                                                <td scope="col">${otherbenefit.insuranceType || '-'}</td>
                                                                <td scope="col">${otherbenefit.planCoverageDescription || '-'}</td>
                                                            </tr>`;
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }

                    if(responseParse != null && typeof responseParse == "object" && Array.isArray(responseParse) && responseParse.length > 0){
                        content += `<div class="eligibility-list-area">
                                        <!--<div class="d-flex justify-content-between align-items-center"></div>-->
                                        <h2 class="d-flex justify-content-between align-items-center">
                                            Next Eligible Dates
                                            <button class="btn btn-link toggle-btn" data-bs-toggle="collapse" data-bs-target="#CDTCodeTable" aria-expanded="false">
                                                <i class="material-icons-outlined icon">keyboard_arrow_right</i>
                                            </button>
                                        </h2>
                                        <div class="collapse" id="CDTCodeTable">
                                            <div class="table-responsive line-items">
                                                <table class="table w-100 p-0" id="CDTCodesTable">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col">Code</th>
                                                            <th scope="col">Last Service Date</th>
                                                            <th scope="col">Next Eligible Service Date</th>
                                                            <th scope="col">Authorization Required</th>
                                                            <th scope="col">Quick Notes</th>
                                                            <th scope="col">Coverage %</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>`;
                                                        responseParse.forEach(parse => {
                                                            content += `<tr>
                                                                <td scope="col">${parse["Code"] ?? '-'}</td>
                                                                <td scope="col">${parse["Lastservicedate"]}</td>
                                                                <td scope="col">${parse["Nexteligibleservicedate"]}</td>
                                                                <td scope="col">${parse["Authorizationrequired"]}</td>
                                                                <td scope="col">${parse["Quicknotes"] ?? '-'}</td>
                                                                <td scope="col">${parse["Coverage%"]}</td>
                                                            </tr>`;
                                                        });
                                        content += `</tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>`;
                    }else{
                        content += `<div class="eligibility-list-area">
                                        <h2>Next Eligible Dates</h2>
                                        <table class="table w-100 p-0" id="CDTCodesTable">
                                            <tr>
                                                <td class="pl-0" colspan="6">Insurance did not provide this information</td>
                                            <tr>
                                        </table>
                                    </div>`;
                    }
                }
                // Append generated content to a container
                $('#eligibility-container').html(content);
            }
            
            let pastpulls = [];
            let getResponse = [];
            let responseParse = [];
            jQuery(document).on('click', '.pre-auth-appointment-list', function() {
                pullEligibilityDataAndHistory(jQuery(this).attr('data-patientId'));
                getFileList($(this).attr("data-external_patient_id"), $(this).attr("data-appointmentid"));
            });
            function pullEligibilityDataAndHistory(patientId){
                getResponse = [];
                responseParse = [];
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('#syncEligibility').removeClass('d-none');
                const formData = new FormData();
                formData.append('patientId', patientId);
                // formData.append('patientId', "daf74a6c-6092-4c9f-8a93-fcec6498f587");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/patient/eligibility-history",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#history-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                jQuery('#eligibility-container').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    jQuery('#history-list').html('');
                    jQuery('#eligibility-container').html('');
                    pastpulls = response.data.histories;
                    if(pastpulls.length == 0) {
                        $('#history-list').html('<p>Previous pull history not found.</p>');
                    } else {
                        eligibilityPullDataDisplay(response.data.histories);
                    }
                    if(response.data.eligibility.length == 0) {
                        $('#eligibility-container').html('<p>Eligibility data not found for selected patient.</p>');
                        jQuery('.eligibility-btn-panel').addClass('d-none');
                    } else {
                        getResponse = response.data.eligibility.response;
                        responseParse = response.data.eligibility.response_parse;
                        displayEligibilityData(response.data.eligibility.response, response.data.eligibility.response_parse, response.data.eligibility.error);
                        // eligibilityParse(response.data.eligibility.response);
                        if (((Array.isArray(getResponse) ? getResponse.length : Object.keys(getResponse || {}).length) > 0 ||
                           (Array.isArray(responseParse) ? responseParse.length : Object.keys(responseParse || {}).length) > 0) &&
                           getResponse?.errors === undefined){
                            jQuery('.eligibility-btn-panel').removeClass('d-none');
                        }
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.eligibility-btn-panel').addClass('d-none');
                    jQuery('#history-list').html('<p>Error while fetching patients past eligibility pulls. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            };
            jQuery(document).on('click', '.pre-auth-appointment-right-list', function() {
                getResponse = [];
                responseParse = [];
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('.pre-auth-appointment-right-list').removeClass('pre-auth-appointment-right-list-selected');
                jQuery(this).addClass('pre-auth-appointment-right-list-selected');
                var created_at = jQuery(this).attr('data-created_at');
                const formData = new FormData();
                formData.append('patientId', jQuery(this).attr('data-patientid'));
                formData.append('created_at', jQuery(this).attr('data-created_at'));
                formData.append('uuid', jQuery(this).attr('data-uuid'));
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/patient/eligibility-details",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#eligibility-container').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    jQuery('#eligibility-container').html('');
                    if (response.success && response.data && response.data.eob) {
                        if (response.data.eob.response) {
                            getResponse = response.data.eob.response;
                            responseParse = response.data.eob.response_parse;
                            displayEligibilityData(response.data.eob.response, response.data.eob.response_parse, response.data.eob.error);
                            // eligibilityParse(response.data.eob.response);
                            if (((Array.isArray(getResponse) ? getResponse.length : Object.keys(getResponse || {}).length) > 0 ||
                               (Array.isArray(responseParse) ? responseParse.length : Object.keys(responseParse || {}).length) > 0) &&
                               getResponse?.errors === undefined) {
                                jQuery('.eligibility-btn-panel').removeClass('d-none');
                            }
                        } else {
                            jQuery('#eligibility-container').html('<p>Unable to retrieve eligibility data for the selected pull.</p>');
                        }
                    } else {
                        jQuery('#eligibility-container').html('<p>Error while fetching selected past eligibility pulls. Please try again later.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#history-list').html('<p>Error while fetching patients past eligibility pulls. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });

            jQuery(document).on('click', '#syncEligibility', function() {
                if($(".user-item-left.pre-auth-appointment-list-selected").attr("data-appointmentid") == undefined || $(".user-item-left.pre-auth-appointment-list-selected").attr("data-appointmentid") == 'undefined'){
                    Swal.fire({
                        position: "top-end",
                        text: "Eligibility sync is work with appointments only.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    return;
                }
                getResponse = [];
                responseParse = [];
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('.pre-auth-appointment-right-list').removeClass('pre-auth-appointment-right-list-selected');
                jQuery('.loading').removeClass('d-none');
                const formData = new FormData();
                formData.append('appointmentId', $(".user-item-left.pre-auth-appointment-list-selected").attr("data-appointmentid"));
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/eligibility/lookup",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    if (response.success) {
                        jQuery('.loading').addClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: response.message || "Something went wrong. Please try after sometime.",
                            showConfirmButton: false,
                            timer: 1000
                        });
                        pullEligibilityDataAndHistory($(".user-item-left.pre-auth-appointment-list-selected").attr("data-patientId"));
                    } else {
                        Swal.fire({
                            position: "top-end",
                            text: "Error while syncing eligibility. Please try again later.",
                            showConfirmButton: false,
                            timer: 1000
                        });
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            jQuery(document).on('click', '#parse-response', function() {
                responseParse = [];
                const formData = new FormData();
                formData.append('patientId', jQuery('.pre-auth-appointment-right-list-selected').attr('data-patientid'));
                formData.append('uuid', jQuery('.pre-auth-appointment-right-list-selected').attr('data-uuid'));
                formData.append('timezone', timeZone);
                
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/eligibility/parse",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    var nextEligibleDates = Array.isArray(response.data) ? response.data : [];
                    var responseParseHtml = '';
                    if(nextEligibleDates.length > 0) {
                        responseParse = nextEligibleDates;
                        jQuery('.client-message').remove();
                        jQuery(this).attr('id', 'parse-success');
                        nextEligibleDates.forEach(parse => {
                            responseParseHtml += `<tr>
                                <td scope="col">${parse?.["Code"] ?? '-'}</td>
                                <td scope="col">${parse?.["Lastservicedate"] ?? '-'}</td>
                                <td scope="col">${parse?.["Nexteligibleservicedate"] ?? '-'}</td>
                                <td scope="col">${parse?.["Authorizationrequired"] ?? '-'}</td>
                                <td scope="col">${parse?.["Quicknotes"] ?? '-'}</td>
                                <td scope="col">${parse?.["Coverage%"] ?? '-'}</td>
                            </tr>`;
                        });
                        jQuery('#nexteligibilitydates').html(responseParseHtml);
                    }else{
                        jQuery('#nexteligibilitydates').html(`<tr><td colspan="6">Insurance did not provide this information.</td></tr>`);    
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#nexteligibilitydates').html(`<tr><td colspan="6">Error while fetching next eligibility dates. Please try again later.</td></tr>`);
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            jQuery('#searchHistory').keyup(function() {
                var searchInput = jQuery(this).val().toLowerCase();
                var filteredHistory = pastpulls.filter(function(history) {
                    return history.created_at.toLowerCase().includes(searchInput);
                });
                eligibilityPullDataDisplay(filteredHistory);
            });
            
            jQuery('#search-patient').click(function() {
                jQuery('.calendar-container').addClass('d-none');
                jQuery('.history-tab').addClass('d-none');
                jQuery('#syncEligibility').addClass('d-none');
                currentDate = getCurrentDate();
                $('#calendarDate').text(formatDate(currentDate));
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('#searchCalander').addClass('d-none');
                jQuery('.list-title').text('Patients List');
                var searchInput = jQuery('#searchPatient').val();
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('GHAccessToken') ?? session('accessToken') }}");
                formData.append('patientName', searchInput);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/patient/list",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.user-list-left').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                jQuery('#history-list').html('<p>Please select a patient to proceed.</p>');
                jQuery('#eligibility-files-list').html('<p>Please select a patient to proceed.</p>');
                jQuery('#eligibility-container').html('<p>Please select an patient to proceed.</p>');
                $.ajax(settings).done(response => {
                    if(response.data && response.data.patients && response.data.patients.length > 0){
                        jQuery('.user-list-left').html('');
                        patientsData = response.data.patients;
                        patientsData.forEach(item => {
                            const userItem = `
                                <div class="user-item-left pre-auth-appointment-list" data-patientId="${item.id}" data-external_patient_id="${item.external_patient_id}" data-patientName="${item.name}">
                                    <h5>${item.name}</h5>
                                    <small>DOB: ${item.birthdate} | ${(item.gender || 'N/A').charAt(0).toUpperCase() + (item.gender || 'N/A').slice(1).toLowerCase()}</small>
                                </div>
                            `;
                            jQuery('.user-list-left').append(userItem);
                        });
                    }else{
                        jQuery('.user-list-left').html('<p>Patient does not match with given name.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error while fetching patients list. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            jQuery(document).on('click', '.pre-auth-appointment-list', function(){
                jQuery('.eligibility-btn-panel').addClass('d-none');
                jQuery('#syncEligibility').removeClass('d-none');
                jQuery('.pre-auth-appointment-list').removeClass('pre-auth-appointment-list-selected');
                jQuery(this).addClass('pre-auth-appointment-list-selected');
                const patientId = jQuery('.pre-auth-appointment-list-selected').attr('data-patientId');
                jQuery('.history-tab').removeClass('d-none');
            });
            
            /* Help Code */
            jQuery(document).on('click', '#get-help', function(){
                const settings = {
                    url: "{{env('API_URL')}}help",
                    method: "GET",
                    timeout: 0,
                    processData: false,
                    contentType: false
                };
                jQuery('#helpModal').modal('show');
                jQuery('.help-body').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    var accordionHTML = '';
                    response.data.forEach(function(item, index) {
                        accordionHTML += `
                        <div class="card">
                            <div class="card-header" id="heading${index}">
                                <h5 class="mb-0">
                                    <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse${index}" aria-expanded="${index === 0 ? 'true' : 'false'}" aria-controls="collapse${index}">
                                        ${item.question}
                                    </button>
                                </h5>
                            </div>
                            <div id="collapse${index}" class="collapse ${index === 0 ? 'show' : ''}" aria-labelledby="heading${index}" data-parent=".help-body">
                                <div class="card-body">
                                    ${item.answer}
                                </div>
                            </div>
                        </div>`;
                    });
                    jQuery('.help-body').html(accordionHTML);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.help-body').html('<p>Error loading help data. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });

            jQuery(document).on('click', '#shceduleUpload', function(){
                const formData = new FormData();
                formData.append('uuid', $(".pre-auth-appointment-right-list-selected").attr("data-uuid"));
                formData.append('timezone', timeZone);
                Swal.fire({
                    position: "top-end",
                    text: 'Request initiated to resend the PDF to EHR.',
                    showConfirmButton: false,
                    timer: 5000
                });
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/external/upload/reset",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    Swal.fire({
                        position: "top-end",
                        text: 'Eligibility PDF upload to EHR has been scheduled.',
                        showConfirmButton: false,
                        timer: 5000
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    console.error("Error:", textStatus, errorThrown);
                });
            });

            $('#downloadPdfBtn').on('click', function() {
                jQuery('.loading').removeClass('d-none');
                $.ajax({
                    url: "{{env('APP_URL')}}/eligibility-pdf",
                    type: 'POST',
                    data: { 
                        response: JSON.stringify(getResponse),
                        parseResponse: JSON.stringify(responseParse)
                    },
                    headers: { 
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    },
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function (response) {
                        jQuery('.loading').addClass('d-none');
                        var carestackPatientId = $(".user-item-left.pre-auth-appointment-list-selected").attr("data-carestackpatientid");
                        var now = new Date();
                        var currentDateTime = String(now.getDate()).padStart(2, '0') +  
                            String(now.getMonth() + 1).padStart(2, '0') +  
                            String(now.getFullYear()).slice(-2) +  
                            String(now.getHours()).padStart(2, '0') +  
                            String(now.getMinutes()).padStart(2, '0') +  
                            String(now.getSeconds()).padStart(2, '0');
                        const blob = new Blob([response], { type: 'application/pdf' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'eligibility-'+carestackPatientId+'-'+currentDateTime+'.pdf';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        Swal.fire({
                            position: "top-end",
                            text: 'Eligibility PDF download successfully.',
                            showConfirmButton: false,
                            timer: 1000
                        });
                    },
                    error: function (xhr) {
                        jQuery('.loading').addClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: "An error occurred. Please try again later or contact support.",
                            showConfirmButton: false,
                            timer: 1000
                        });
                    }
                });
            });

            jQuery(document).on('click', '.toggle-btn', function () {
                const icon = $(this).find('.icon');
                const iconName = icon.text();
                const id = $(this).attr('data-bs-target');
                // $('.toggle-btn .icon').text('keyboard_arrow_right');
                // $('.collapse').collapse('hide');
                if(iconName === 'keyboard_arrow_right'){
                    $(id).collapse('show');
                    icon.text('keyboard_arrow_down');
                }else{
                    $(id).collapse('hide');
                    icon.text('keyboard_arrow_right');
                }
            });

            // Expand All
            jQuery(document).on('click', '#expandAll', function () {
                $('.collapse').collapse('show');
                $('.toggle-btn .icon').text('keyboard_arrow_down');
                $('.toggle-btn#parse-response').trigger('click');
            });

            // Collapse All
            jQuery(document).on('click', '#collapseAll', function () {
                $('.collapse').collapse('hide');
                $('.toggle-btn .icon').text('keyboard_arrow_right');
            });

            $('.collapse').on('show.bs.collapse', function() {
                $('.collapse.show').not(this).collapse('hide');
                $(this).prev('a').find('.fas').removeClass('fa-angle-down').addClass('fa-angle-up');
            }).on('hide.bs.collapse', function() {
                $(this).prev('a').find('.fas').removeClass('fa-angle-up').addClass('fa-angle-down');
            });
            
            jQuery(document).on('change', '#fileInput', function () {
                var file = $('#fileInput')[0].files[0];
                console.log(file);
                var maxSize = 32 * 1024 * 1024; // 32MB for images and PDFs
                var allowedTypes = ['application/pdf'];
                var valid = true;
                var formData = new FormData();
                if (!file) {
                    Swal.fire({
                        icon: 'error',
                        title: 'File Validation Failed!',
                        text: 'Please select a file to upload.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return;
                }
                if (!allowedTypes.includes(file.type)) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid File Type',
                        text: 'Invalid file type: ' + file.name + '. Allowed file type are .pdf.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }

                if (file.size > maxSize) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid File Size',
                        text: `The file ${file.name} exceeds the maximum allowed size of 32MB.`,
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return;
                }

                formData.append('file', file);
                formData.append("uuid", jQuery('.pre-auth-appointment-right-list-selected').attr('data-uuid'));
                formData.append("external_patient_id", $('.pre-auth-appointment-right-list-selected').attr('data-external_patient_id'));
                formData.append("external_appointment_id", $('.pre-auth-appointment-right-list-selected').attr('data-external_appointment_id'));
                formData.append("appointment_id", $('.user-item-left.pre-auth-appointment-list-selected').attr('data-appointmentid'));
                formData.append('timezone', timeZone);
                jQuery('.loading').removeClass('d-none');
                // AJAX request to upload file
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/eligibility/upload",
                    timeout: 0,
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    mimeType: "multipart/form-data",
                    processData: false,
                    success: function (response) {
                        jQuery('.loading').addClass('d-none');
                        // jQuery('#upload-container').addClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: 'The eligibility PDF has been successfully uploaded to the EHR.',
                            showConfirmButton: false,
                            timer: 5000
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        jQuery('.loading').addClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: 'Something went wrong. Please try again later.',
                            showConfirmButton: false,
                            timer: 5000
                        });
                        console.log(jqXHR, errorThrown);
                        console.log('File upload failed. Please try again.');
                    }
                });
            });

            function getFileList(external_patient_id, external_appointment_id) {
                const formData = new FormData();
                formData.append('external_patient_id', external_patient_id);
                formData.append('external_appointment_id', external_appointment_id);
                formData.append('timezone', timeZone);
                jQuery('#eligibility-files-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/eligibility/file-list",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    const fileList = $('#eligibility-files-list');
                    fileList.empty();
                    const files = response.data;
                    if(files.length > 0) {
                        $.each(files, function(index, file) {
                            // const lastPullTime = formatDateTime(lastpull.created_at, {format:'full',  locale:'en-US', hour12:true});
                            $('#eligibility-files-list').append(`
                                <div title="${file.eligibility_file}" class="right-bottom-border pre-auth-appointment-right-file-list" 
                                    data-eligibility_file="${file.eligibility_file}"
                                    data-eligibility_id="${file.eligibility_id}">
                                    <span>${file.eligibility_file}</span>
                                </div>
                            `);
                        });
                    } else {
                        jQuery('#eligibility-files-list').html(`<p>No files have been uploaded yet.</p>`);
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#eligibility-files-list').html(`<p>${textStatus}</p>`);
                    console.error("Error:", textStatus, errorThrown);
                });
            }

            $(document).on('click', '.pre-auth-appointment-right-file-list', function(){
                const eligibilityURL = $(this).attr('data-eligibility_file');
                getEligibility(eligibilityURL);
            });
            
            $(document).on('click', '.eligibility-modal-close', function(){
                $('.eligibilityFile-data').html('');
                jQuery('#eligibilityFile').modal('hide');
            });

            /*Report by URL*/
            function getEligibility(eligibilityURL) {
                const formData = new FormData();
                formData.append('eligibilityURL', eligibilityURL);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}dentalxchange/eligibility/details",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#eligibilityFile').modal('show');
                jQuery('.eligibilityFile-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    if(response.data.contentType.includes('image') || response.data.contentType.includes('jpg') || response.data.contentType.includes('jpeg') || response.data.contentType.includes('png') || response.data.contentType.includes('heic') || response.data.contentType.includes('heif')){
                        $('.eligibilityFile-data').html('<img style="width: 100%;" src="data:'+response.data.contentType+';base64,'+response.data.data+'">');
                    } else {
                        $('.eligibilityFile-data').html('<iframe style="height: 90vh; width: 100%;" src="data:application/'+response.data.contentType+';base64,'+response.data.data+'"></iframe>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('.eligibilityFile-data').html('');
                    jQuery('#eligibilityFile').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
        });
        
        function filterEligibilityOLD(searchBoxId) {
            // let tables = ["CoInsTable", "CDTCodesTable", "DeductTable", "MaximumTable", "NotCovered", "OtherBenefit", "benefitsTable"];
            let input = document.getElementById(searchBoxId).value.toLowerCase().trim();
            searchTables.forEach(tableId => {
                let table = document.getElementById(tableId);
                if (!table) return;
                let rows = table.querySelectorAll("tbody tr");
                if (input === "") {
                    rows.forEach(row => row.style.display = "");
                } else {
                    let searchTerms = input.split(",").map(term => term.trim()).filter(term => term !== "");
                    rows.forEach(row => {
                        let rowText = Array.from(row.getElementsByTagName("td")).map(td => td.textContent.toLowerCase()).join(" ");
                        let match = searchTerms.some(term => rowText.includes(term));
                        row.style.display = match ? "" : "none";
                    });
                }
            });
        }

        function filterEligibility(searchBoxId) {
            let input = document.getElementById(searchBoxId).value.toLowerCase().trim();
            let inNetworkChecked = document.getElementById("inNetworkCheckbox")?.checked;
            let outNetworkChecked = document.getElementById("outNetworkCheckbox")?.checked;

            let searchTerms = input.split(",").map(term => term.trim().toLowerCase()).filter(term => term !== "");

            searchTables.forEach(tableId => {
                let table = document.getElementById(tableId);
                if (!table) return;

                let tbody = table.querySelector("tbody");
                let rows = tbody.querySelectorAll("tr");

                // Remove old "no data" row if present
                let oldNoData = tbody.querySelector(".no-data-row");
                if (oldNoData) oldNoData.remove();

                let matchCount = 0;

                rows.forEach(row => {
                    let tds = Array.from(row.getElementsByTagName("td"));
                    if (tds.length === 0) return;

                    let rowText = tds.map(td => td.textContent.toLowerCase()).join(" ");
                    let hasInNetwork = rowText.includes("in-network");
                    let hasOutNetwork = rowText.includes("out-of-network");

                    let matchSearch = searchTerms.length === 0 || searchTerms.some(term => rowText.includes(term));
                    let matchCheckbox =
                        (!inNetworkChecked && !outNetworkChecked) ||
                        (inNetworkChecked && hasInNetwork) ||
                        (outNetworkChecked && hasOutNetwork);

                    let show = matchSearch && matchCheckbox;
                    row.style.display = show ? "" : "none";
                    if (show) matchCount++;
                });

                // If nothing matched, show message
                if (matchCount === 0) {
                    let colCount = table.querySelectorAll("thead tr th").length || 5;
                    let noDataRow = document.createElement("tr");
                    noDataRow.className = "no-data-row";
                    noDataRow.innerHTML = `<td colspan="${colCount}" class="text-center text-muted">No matching records found</td>`;
                    tbody.appendChild(noDataRow);
                }
            });
        }
    </script>
@endpush