@extends('app')
@section('title', 'Med-X | EOB')
@push('styles')
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker3.min.css">
    <link rel="stylesheet" href="{{env('APP_URL')}}/public/assets/css/resizable.css">
@endpush

@section('content')
    <main class="container-fluid eob-container">
        <div class="row align-items-center logo-row pb-2">
            <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 d-flex justify-content-between align-items-center">
                <div class="d-flex">
                    <div class="dynamic-title pt-1">
                            <h4 class="secondary-color">Validate EOB</h4>
                    </div>
                    <div class="pl-3 eob-upload-container">
                        <div class="eob-upload-area" id="uploadArea" title="Only PDF files are allowed, and each file must be a maximum of 10 MB in size.">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p class="pl-3">Upload Files</p>
                            <input type="file" id="fileInput" name="files[]" multiple accept="application/pdf">
                        </div>
                    </div>
                </div>
                <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 class="panel-container">
            <div class="col-sm-2 pat-list pl-0 mr-2">
                <h3 class="font-weight-light mb-3">Patient's List</h3>
                <div class="form-group mb-1">
                    <div class="input-group">
                        <select id="status" class="form-control">
                            <option value="Pending" selected>Pending Patients</option>
                            <option value="Validated">Validated Patients</option>
                        </select>
                    </div>
                </div>
                <div class="form-group mb-0">
                    <div class="datepicker date input-group">
                        <input type="text" placeholder="Upload Date" class="form-control" id="processingDate" value="">
                        <div class="input-group-append">
                            <span class="input-group-text"><i class="fa-solid fa-calendar-days"></i></span>
                        </div>
                    </div>
                </div>
                <div class="eob-user-list user-list-left">
                    <div class="uri-list"><p>Patients not found</p></div>
                </div>
            </div>
            <div class="preview-box panel-left">
                <div class="center-box">
                    <div class="d-flex justify-content-between mb-3 align-items-center">
                        <h3 class="font-weight-light mb-0">Document Preview</h3>
                        <span class="upload_on pr-2"></span>
                    </div>
                    <div id="main" class="document-preview">
                        <div class="accordion" id="pdflist">
                            <p>Please select a patient to view the list of uploaded document previews.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="splitter"></div>
            <div class="doc-detail panel-right">
                <div class="fullscreen">
                    <h3 class="font-weight-light mb-3">Document Details</h3>
                    <div>
                        <i class="material-icons filter-icon">filter_list</i>
                        <div style="display:none;" id="filterDropdown">
                            <h6>Filter Columns</h6>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="procedure_code" value="procedure_code" {{in_array('procedure_code', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="procedure_code">Service Code</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="date_of_service" value="date_of_service" {{in_array('date_of_service', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="date_of_service">Date of Service</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="description" value="description" {{in_array('description', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="description">Service Description</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="units" value="units" {{in_array('units', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="units">Units</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="amount_billed" value="amount_billed" {{in_array('amount_billed', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="amount_billed">Billed Amount</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="amount_paid" value="amount_paid" {{in_array('amount_paid', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="amount_paid">Paid Amount</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="deductible" value="deductible" {{in_array('deductible', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="deductible">Deduction Applied</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="copay" value="copay" {{in_array('copay', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="copay">COPAY</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="out_of_pocket" value="out_of_pocket" {{in_array('out_of_pocket', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="out_of_pocket">Out Of Pocket</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="remark_code" value="remark_code" {{in_array('remark_code', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="remark_code">Remark Code</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="fields[]" id="remark_explanation" value="remark_explanation" {{in_array('remark_explanation', session()->get(session('PractitionerId'))) ? 'checked' : ''}} >
                                <label class="form-check-label" for="remark_explanation">Remark Explanation</label>
                            </div>
                            <!-- Add more columns as needed -->
                            <button class="btn btn-primary primary-bg-color btn-sm mt-2" id="saveColumns">Save</button>
                            <button class="btn btn-primary custom-cancel-btn btn-sm mt-2" id="columnfilterclose">Cancel</button>
                        </div>
                        <i class="material-icons" id="screenMode">fullscreen</i>
                    </div>
                </div>
                <div class="document-details right">
                    <p>Please select document to see details.</p>
                </div>
            </div>
            <div id="resize-overlay"></div>
        </div>
        <div id="setting-screen" class="setting-screen d-none">
            <div class="setting-header">
                <h6 class="mb-0">Settings</h6>
                <i id="close-setting" class="material-icons close-setting-icon close-setting">close</i>
            </div>
            <div class="setting-body">
                <div class="row">
                    <div class="col-sm-12">
                        <label for="customer-id" class="mb-1">Customer Id</label>
                        <input type="text" id="customer-id" class="form-control mb-1" value="{{env('GEN_CUSTOMER_ID', '47b0cfff-4833-415a-8c3b-667dfb086007')}}" placeholder="Enter customer id here">
                    </div>
                    <div class="col-sm-12">
                        <label for="co-pilot" class="mb-1">Co-Pilot</label>
                        <input type="text" id="co-pilot" class="form-control mb-1" value="{{env('GEN_PROJECT_ID', '43fb53c0-5ecc-4fca-9913-38990819143c')}}" placeholder="Enter co-pilot here">
                    </div>
                    <div class="col-sm-12">
                        <label for="stage" class="mb-1">Stage</label>
                        <input type="text" id="stage" class="form-control mb-1" value="{{env('STAGE')}}" placeholder="Enter stage id here">
                    </div>
                    <div class="col-sm-12">
                        <label for="query" class="mb-1">Query</label>
                        <input type="text" id="query" class="form-control mb-1" value="{{env('QUERY', 'give the answer of***')}}" placeholder="Enter query here">
                    </div>
                    <div class="col-sm-12">
                        <div class="setting-btn">
                            <button class="btn btn-primary primary-bg-color" id="save-settings">Submit</button>
                            <button class="btn btn-primary secondary-bg-color close-setting">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
@endsection
@push('scripts')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <script src="{{env('APP_URL')}}/public/assets/js/jquery-resizable.js"></script>
    <script>
        $(document).ready(function() {
            const md = window.markdownit();
            var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
            var displayColumns = @json(session()->get(session('PractitionerId')));
            const tableColumn = ['procedure_code', 'date_of_service', 'description', 'units', 'amount_billed', 'amount_paid', 'deductible', 'copay', 'out_of_pocket', 'remark_code', 'remark_explanation'];
            $(".panel-left").resizable({
                handleSelector: ".splitter",
                resizeHeight: false,
                onDragStart: function() {
                    $("#resize-overlay").show();
                },
                onDragEnd: function() {
                    $("#resize-overlay").hide();
                }
            });
    
            $(".panel-top").resizable({
                handleSelector: ".splitter-horizontal",
                resizeWidth: false,
                onDragStart: function() {
                    $("#resize-overlay").show();
                },
                onDragEnd: function() {
                    $("#resize-overlay").hide();
                }
            });
            let patientArray = [];
            $('.datepicker').datepicker({
                language: "es",
                autoclose: true,
                clearBtn: true,
                format: "dd/mm/yyyy",
                endDate: new Date(),
                datesDisabled: [],
            }).on('changeDate', function(e) {
                var selectedDate = e.format('dd/mm/yyyy');
                jQuery('#processingDate').val(selectedDate);
                getBigQueryList();
            }).on('clearDate', function() {
                jQuery('#processingDate').val('');
                getBigQueryList();
            });
        
            $('#status').on('change', function () {
                getBigQueryList();
            });
        
            $('#fileInput').on('change', function () {
                var files = $('#fileInput')[0].files;
                var maxSize = 50 * 1024 * 1024; // 50MB for images and PDFs
                var allowedTypes = ['application/pdf'];
                var valid = true;
                var formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                if (files.length === 0) {
                    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;
                }
                jQuery('.loading').removeClass('d-none');
                $.each(files, function (index, file) {
                    if ($.inArray(file.type, allowedTypes) === -1) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Type',
                            text: 'Invalid file type: ' + file.name + '. Allowed file type are .jpeg, .png or .pdf.',
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        jQuery('.loading').addClass('d-none');
                        return false;
                    }
        
                    // Validate file size
                    if (file.size > maxSize) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Size',
                            text: 'Please select allowed file size. File size must be less than 32MB for file: ' + file.name,
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        jQuery('.loading').addClass('d-none');
                        return false;
                    }
        
                    formData.append('files[]', file);
                });
                if (!valid) {
                    return;
                }
                
                // AJAX request to upload file
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/upload-file",
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    success: function(response) {
                        Swal.fire({
                            position: "top-end",
                            text: "File uploaded successfully",
                            showConfirmButton: false,
                            timer: 2000
                        });
                        jQuery('#processingDate').val('');
                        window.location.reload();
                    },
                    error: function(xhr) {
                        Swal.fire({
                            position: "top-end",
                            text: "File uploadation failed",
                            showConfirmButton: false,
                            timer: 2000
                        });
                        jQuery('.loading').addClass('d-none');
                    }
                });
            });
            
            // function getAllDatesExcept(selectableDates) {
            //     let allDates = [];
            //     let today = new Date();
            //     let start = new Date(today.getFullYear(), today.getMonth() - 2, 1);
            //     let end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        
            //     for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
            //         let day = d.getDate().toString().padStart(2, '0');
            //         let month = (d.getMonth() + 1).toString().padStart(2, '0');
            //         let year = d.getFullYear();
            //         let formattedDate = `${day}/${month}/${year}`;
            //         if (!selectableDates.includes(formattedDate)) {
            //             allDates.push(formattedDate);
            //         }
            //     }
            //     return allDates;
            // }
            
            const patientIntervals = {};
            function getBigQueryList() {
                jQuery('.upload_on').text('');
                jQuery('#pdflist').html('<p>Please select a patient to view the list of uploaded document previews.</p>');
                jQuery('.document-details').html('<p>Please select document to see details.</p>');
                $('.uri-list').empty();
                $('.uri-list').append(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('date', jQuery('#processingDate').val());
                formData.append('status', jQuery('#status').val());
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/get-patient-list",
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    success: function(response) {
                        $('.uri-list').empty();
                        if(response.data.length > 0){
                            const disabledDates = [];
                            $.each(response.data, function(index, patient) {
                                var timerHtml = '(Processing)';
                                let date = patient.created.split(' ')[0];
                                const [year, month, day] = date.split('-');
                                disabledDates.push(`${day}/${month}/${year}`);
                                if(patient.latestData != undefined && patient.latestData == false){
                                    const patientName = patient.patient_name;
                                    var functionNameString = patientName.toLowerCase().replace(/\s+/g, '');
                                    const intervalName = functionNameString + 'Interval';
                                    const updateTimer = () => {
                                        functionNameString = functionNameString;
                                        const currentTimeNow = new Date();
                                        const currentTime = new Date(currentTimeNow.getTime() + currentTimeNow.getTimezoneOffset() * 60000);
                                        const serverTime = new Date(patient.created);
                                        const targetTime = new Date(serverTime.getTime() + 3600000);
                                        const remainingTime = (targetTime - currentTime) / 1000;
                                        if (remainingTime > 0) {
                                            const timePassedPercentage = (3600 - remainingTime) / 3600;
                                            const rotationDegrees = timePassedPercentage * 360;
                                            $("#" + functionNameString + "-circleTimer").css("transform", `rotate(${rotationDegrees}deg)`);
                                            $("#" + functionNameString + "-circleTimer").css("background", `conic-gradient(#fff ${360 - rotationDegrees}deg, #28a745 ${360 - rotationDegrees}deg)`);
                                        } else {
                                            $("#" + functionNameString + "-wrapper").remove();
                                            clearInterval(patientIntervals[functionNameString]);
                                        }
                                    };
                                    patientIntervals[functionNameString] = setInterval(updateTimer, 1000);
                                    updateTimer();
                                    timerHtml = `<div id="${functionNameString}-wrapper" title="Processing"><div class="circle-timer" id="${functionNameString}-circleTimer"></div></div>`;
                                }
                                const patientList = `<div class="right-bottom-border patientList" data-patientId="${patient.id}" data-fileId="${patient.eob_file_id}" data-summaryId="${patient.eob_summary_id}">
                                    <span id="eob-report-file" class="m-0"><span>${patient.patient_name}</span>${patient.latestData != undefined && patient.latestData ? '' : timerHtml}</span>
                                </div>`;
                                $('.uri-list').append(patientList);
                            });
                            // $('.datepicker').datepicker('setDatesDisabled', getAllDatesExcept(disabledDates));
                        } else {
                            $('.uri-list').html('<p>Patients not found</p>');
                        }
                        
                    },
                    error: function(xhr) {
                        $('.uri-list').html('<p>An error occurred: ' + xhr.responseText + '</p>');
                    }
                });
            }
            getBigQueryList();
            
            jQuery(document).on('click', '.patientList', function(){
                jQuery('.upload_on').text('');
                jQuery('.document-details').html('<p>Please select document to see details.</p>');
                jQuery('.patientList').removeClass('patient-selected');
                jQuery(this).addClass('patient-selected');
                var patientId = jQuery(this).attr('data-patientId');
                var fileId = jQuery(this).attr('data-fileId');
                var summaryId = jQuery(this).attr('data-summaryId');
                $('#pdflist').empty();
                $('#pdflist').html(`<div class="loader-container">
                    <div class="loader" id="loader"></div>
                </div>`);
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', patientId);
                formData.append('fileId', fileId);
                formData.append('summaryId', summaryId);
                formData.append('date', jQuery('#processingDate').val());
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/get-patient-data",
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    success: function(response) {
                        $('#pdflist').empty();
                        $.each(response.data, function(index, file) {
                            var fileList = `
                                <span class="d-none patient-details">${JSON.stringify(file)}</span>
                                <div class="pdfview"></div>
                            `;
                            $('#pdflist').append(fileList);
                            patientDetails('.patient-details', file.uri.split('/').pop(), file.content_type);
                            return;
                        });
                    },
                    error: function(xhr) {
                        $('#pdflist').html('<p>An error occurred: ' + xhr.responseText + '</p>');
                    }
                });
            });
            
            function documentDetails(clsName) {
                var details = jQuery(clsName).text();
                $('.document-details').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                if(details.length > 20){
                    var detailObject = JSON.parse(details);
                    if(typeof detailObject === 'object') {
                        var tableData = '';
                        const oldData = detailObject.patient.latestData;
                        const patientId = detailObject.patient.id;
                        const checkData = detailObject.patient.id;
                        const utcDate = new Date(detailObject.upload_on);
                        const localDateStr = utcDate.toLocaleString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        });
                        jQuery('.upload_on').text('Uploaded on: '+localDateStr);
                        // const checkData = detailObject.summary.id;
                        if(detailObject.summary.validation_status == 'Validated') { patientArray.push(checkData); }
                        const lineData = detailObject.procedures;
                        lineData.forEach(function(item, index) {
                            const fullRemark = item.remark_explanation || 'N/A';
                            const remarkLength = fullRemark.length;
                            const lengthLimit = 85;
                            let sortString = fullRemark;
                            let isMore = false;
                            if(remarkLength > lengthLimit){
                                isMore = true;
                                sortString = fullRemark.substring(0, 70) + '... ';
                            }
                            tableData += `<tr>
                                            <td class="procedure_code">${item.procedure_code || 'N/A'}</td>
                                            <td class="date_of_service">${item.date_of_service || 'N/A'}</td>
                                            <td class="description">${item.description || 'N/A'}</td>
                                            <td class="units">${item.units || 'N/A'}</td>
                                            <td class="amount_billed"><input type="number" step="0.01" id="amount_billed-${index}" data-where="${item.id}" data-fieldName="amount_billed" class="amount_billed-input ${oldData && !patientArray.includes(checkData) ? 'edit-input' : ''} d-none" value="${parseFloat(item.amount_billed)}" /> <span class="${oldData && !patientArray.includes(checkData) ? 'display-data pointer' : 'no-drop'}">${(item.amount_billed === null || item.amount_billed === undefined) ? '$0.00' : (item.amount_billed.toString().includes('$') ? item.amount_billed : '$' + item.amount_billed)}</span></td>
                                            <td class="amount_paid"><input type="number" step="0.01" id="amount_paid-${index}" data-where="${item.id}" data-fieldName="amount_paid" class="amount_paid-input ${oldData && !patientArray.includes(checkData) ? 'edit-input' : ''} d-none" value="${parseFloat(item.amount_paid)}" /> <span class="${oldData && !patientArray.includes(checkData) ? 'display-data pointer' : 'no-drop'}">${(item.amount_paid === null || item.amount_paid === undefined) ? '$0.00' : (item.amount_paid.toString().includes('$') ? item.amount_paid : '$' + item.amount_paid)}</span></td>
                                            <td class="deductible"><input type="number" step="0.01" id="deductible-${index}" data-where="${item.id}" data-fieldName="deductible" class="deductible-input ${oldData && !patientArray.includes(checkData) ? 'edit-input' : ''} d-none" value="${parseFloat(item.deductible)}" /> <span class="${oldData && !patientArray.includes(checkData) ? 'display-data pointer' : 'no-drop'}">${(item.deductible === null || item.deductible === undefined) ? '$0.00' : (item.deductible.toString().includes('$') ? item.deductible : '$' + item.deductible)}</span></td>
                                            <td class="copay"><input type="number" step="0.01" id="copay-${index}" data-where="${item.id}" data-fieldName="copay" class="copay-input ${oldData && !patientArray.includes(checkData) ? 'edit-input' : ''} d-none" value="${parseFloat(item.copay)}" /> <span class="${oldData && !patientArray.includes(checkData) ? 'display-data pointer' : 'no-drop'}">${(item.copay === null || item.copay === undefined) ? '$0.00' : (item.copay.toString().includes('$') ? item.copay : '$' + item.copay)}</span></td>
                                            <td class="out_of_pocket"><input type="number" step="0.01" id="out_of_pocket-${index}" data-where="${item.id}" data-fieldName="out_of_pocket" class="out_of_pocket-input ${oldData && !patientArray.includes(checkData) ? 'edit-input' : ''} d-none" value="${parseFloat(item.out_of_pocket)}" /> <span class="${oldData && !patientArray.includes(checkData) ? 'display-data pointer' : 'no-drop'}">${(item.out_of_pocket === null || item.out_of_pocket === undefined) ? '$0.00' : (item.out_of_pocket.toString().includes('$') ? item.out_of_pocket : '$' + item.out_of_pocket)}</span></td>
                                            <td class="remark_code">${item.remark_code || 'N/A'}</td>
                                            <td class="remark_explanation">
                                                <p class="mb-0"><span class="remark">${sortString}</span>${isMore ? `<a href="javascript:void(0)" class="read-condition" data-sort-content="${encodeURIComponent(sortString)}" data-full-content="${encodeURIComponent(fullRemark+' ')}">Read more</a>` : ''}</p>
                                            </td>
                                        </tr>`;
                        });
                        var data = `<div class="eob-user-item border-0 p-0">
                                        <div class="d-flex justify-content-between">
                                            <div class="d-grid">
                                                <h6 class="primary-color mb-2">${detailObject.patient.patient_name}</h6>
                                                <span>CLAIM NUMBER: ${detailObject.patient.claim_id || 'N/A'}</span>
                                                ${detailObject.patient.date_of_birth != null ? `<span>DATE OF BIRTH: ${detailObject.patient.date_of_birth || 'N/A'}</span>` : ''}
                                            </div>
                                            ${oldData ? 
                                                `<button type="button" class="btn btn-primary primary-bg-color verify-btn ${detailObject.summary.validation_status == 'Validated' ? 'validated' : 'validate' }" data-patientId="${patientId}" data-ID="${detailObject.summary.id}">${detailObject.summary.validation_status == 'Validated' ? 'Validated' : 'Mark validated' }</button>`
                                            :
                                                `<button type="button" class="btn btn-primary primary-bg-color verify-btn validated">${detailObject.summary.validation_status == 'Validated' ? 'Validated' : 'Mark validated' }</button>`
                                            }
                                        </div>
                                    </div>
                                    <div class="eob-user-item d-grid border-0 p-0 mt-4">
                                        <h6 class="primary-color mb-2">${detailObject.summary.insurance_company || 'N/A'}</h6>
                                        <span>PROVIDER NAME: ${detailObject.summary.provider_name || 'N/A'}</span>
                                        <span>GROUP NUMBER: ${detailObject.patient.group_number || 'N/A'}</span>
                                    </div>
                                    <div class="table-responsive line-items">
                                        <table class="table w-100 p-0 mt-4">
                                            <thead>
                                                <tr>
                                                    <th class="procedure_code" scope="col">Service Code</th>
                                                    <th class="date_of_service" scope="col">Date of Service</th>
                                                    <th class="description" scope="col" class="text-nowrap">Service Description</th>
                                                    <th class="units" scope="col">Units</th>
                                                    <th class="amount_billed" scope="col">Billed Amount</th>
                                                    <th class="amount_paid" scope="col">Paid Amount</th>
                                                    <th class="deductible" scope="col">Deduction Applied</th>
                                                    <th class="copay" scope="col">COPAY</th>
                                                    <th class="out_of_pocket" scope="col">Out Of Pocket</th>
                                                    <th class="remark_code" scope="col">Remark Code</th>
                                                    <th class="remark_explanation" scope="col" style="min-width: 300px;">Remark Explanation</th>
                                                </tr>
                                            </thead>
                                            <tbody id="pdf-data">${tableData}</tbody>
                                            <tfoot>
                                                <tr>
                                                    <th colspan="11">
                                                        <span class="foot-width">Total Covered Amount</span>
                                                        <span>${(detailObject.patient.total_covered_amount === null || detailObject.patient.total_covered_amount === undefined) ? '$0.00' : (detailObject.patient.total_covered_amount.toString().includes('$') ? detailObject.patient.total_covered_amount : '$' + detailObject.patient.total_covered_amount)}</span>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="11">
                                                        <span class="foot-width">Total Allowable Charges</span>
                                                        <span>${(detailObject.patient.total_allowable_charges === null || detailObject.patient.total_allowable_charges === undefined) ? '$0.00' : (detailObject.patient.total_allowable_charges.toString().includes('$') ? detailObject.patient.total_allowable_charges : '$' + detailObject.patient.total_allowable_charges)}</span>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="11">
                                                        <span class="foot-width">Total Reduction</span>
                                                        <span>${(detailObject.patient.total_alt_ben_reduction === null || detailObject.patient.total_alt_ben_reduction === undefined) ? '$0.00' : (detailObject.patient.total_alt_ben_reduction.toString().includes('$') ? detailObject.patient.total_alt_ben_reduction : '$' + detailObject.patient.total_alt_ben_reduction)}</span>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="11">
                                                        <span class="foot-width">Total Deduction</span>
                                                        <span>${(detailObject.patient.total_deductible === null || detailObject.patient.total_deductible === undefined) ? '$0.00' : (detailObject.patient.total_deductible.toString().includes('$') ? detailObject.patient.total_deductible : '$' + detailObject.patient.total_deductible)}</span>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="11">
                                                        <span class="foot-width">Total Charges</span>
                                                        <span>${(detailObject.patient.total_charges === null || detailObject.patient.total_charges === undefined) ? '$0.00' : (detailObject.patient.total_charges.toString().includes('$') ? detailObject.patient.total_charges : '$' + detailObject.patient.total_charges)}</span>
                                                    </th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>`;
                        $('.document-details').html(data);
                        hideShowColumn(displayColumns);
                    } else {
                        $('.document-details').html('<p>Data Not Found</p>');
                    }
                }else{
                    $('.document-details').html('<p>Data Not Found</p>');
                }
            }
            
            jQuery(document).on('click', '.read-condition', function(e) {
                e.preventDefault();
                const link = jQuery(this);
                const remark = link.siblings('.remark');
                if (link.text() === 'Read more') {
                    console.log(decodeURIComponent(link.attr('data-full-content')));
                    remark.text(decodeURIComponent(link.attr('data-full-content')));
                    link.text('Read less');
                } else {
                    remark.text(decodeURIComponent(link.attr('data-sort-content')));
                    link.text('Read more');
                }
            });

            jQuery(document).on('click', '.filter-icon', function() {
                $('#filterDropdown').toggle();
            });
            jQuery(document).on('click', '#columnfilterclose', function() {
                $('#filterDropdown').hide();
            });
            function hideShowColumn(displayColumns) {
                jQuery.each(tableColumn, function(index, column) {
                    if (displayColumns.includes(column)) {
                        jQuery('.' + column).removeClass('d-none');
                    } else {
                        $('.' + column).addClass('d-none');
                    }
                });
            }
            jQuery(document).on('click', '#saveColumns', function(){
                var selectedFields = [];
                $('input[name="fields[]"]:checked').each(function() {
                    selectedFields.push($(this).val());
                });
                $.ajax({
                    url: "{{env('APP_URL')}}/save/session",
                    type: 'POST',
                    data: {
                        _token: "{{ csrf_token() }}",
                        fields: selectedFields
                    },
                    success: function(response) {
                        displayColumns = response.session;
                        $('#filterDropdown').toggle();
                        hideShowColumn(selectedFields);
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', error);
                        Swal.fire({
                            position: "top-end",
                            text: 'Something went wrong. Please try again later!',
                            showConfirmButton: false,
                            timer: 2000
                        });
                        $('#filterDropdown').toggle();
                    }
                });
            });
            
            $(document).on('click', '.display-data', function() {
                $(this).addClass('d-none');
                $(this).siblings('.edit-input').val(parseFloat($(this).text().replace('$',''))).removeClass('d-none').focus();
            });

            function patientDetails(clsName, fileName, contentType) {
                documentDetails(clsName);
                var page_number = 1;
                var details = jQuery(clsName).text();
                if(details.length > 20){
                    var detailObject = JSON.parse(details);
                    if(typeof detailObject === 'object') {
                        page_number = detailObject.procedures[0].page_number;
                    }
                }
                $('.pdfview').empty();
                $('.pdfview').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/sign-url/"+encodeURIComponent(fileName),
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    success: function(response) {
                        $('.pdfview').empty();
                        const documentDetail = `<embed src="${response.data}#page=${page_number}&toolbar=1&amp;navpanes=0&amp;scrollbar=0" type="${contentType}" frameborder="0" scrolling="auto" width="100%" height="730px">`;
                        $('.pdfview').html(documentDetail);
                    },
                    error: function(xhr) {
                        $('.pdfview').html('<p>An error occurred: ' + xhr.responseText + '</p>');
                    }
                });
            }

            jQuery(document).on('click', '.validate', function(){
                var ID = jQuery(this).attr('data-ID');
                var patientId = jQuery(this).attr('data-patientId');
                $('.validate').text('Validating...');
                $('.verify-btn').removeClass('validate').addClass('validated');
                
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/verified/" + encodeURIComponent(ID) + "/" + encodeURIComponent(patientId),
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    success: function(response) {
                        $('.verify-btn').text('Validated');
                        patientArray.push(patientId);
                        $('.pointer').addClass('no-drop').removeClass('display-data');
                        Swal.fire({
                            position: "top-end",
                            text: response.message,
                            showConfirmButton: false,
                            timer: 2000
                        });
                        jQuery('.upload_on').text('');
                        jQuery('#pdflist').html('<p>Please select a patient to view the list of uploaded document previews.</p>');
                        jQuery('.document-details').html('<p>Please select document to see details.</p>');
                        jQuery('.patient-selected').remove();
                    },
                    error: function(xhr) {
                        // let errorMessage = "An error occurred. Please try again.";
                        // try {
                        //     let response = JSON.parse(xhr.responseText);
                        //     console.log(response, typeof response);
                        //     if (response.error && response.error.message) {
                        //         errorMessage = response.error.message;
                        //     }
                        // } catch (e) {
                        //     console.error("Error parsing response:", e);
                        // }
                        Swal.fire({
                            position: "top-end",
                            text: xhr.responseText,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                });
            });

            var known = @json(session()->get('known'));
            $(document).on('focusout', '.edit-input', function() {
                var $input = $(this);
                var where = $input.attr('data-where');
                var fieldName = $input.attr('data-fieldName');
                var fieldValue = $input.val();
                var oldValue = parseFloat($input.siblings('.display-data').text().replace('$',''));
                $(this).addClass('d-none');
                if(oldValue == parseFloat(fieldValue)) { $input.siblings('.display-data').removeClass('d-none'); return; }
                $input.after(`<div class="edit-loader">
                                <div class="loader" id="loader"></div>
                            </div>`);
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('where', where);
                formData.append('fieldName', fieldName);
                formData.append('fieldValue', fieldValue);
                $.ajax({
                    url: "{{env('API_URL')}}dentalxchange/update/" + encodeURIComponent(where),
                    method: 'POST',
                    contentType: false,
                    processData: false,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    data: formData,
                    success: function(response) {
                        $input.siblings('.display-data').text('$'+fieldValue);
                        $input.closest('td').addClass('bg-light-green');
                        $('.edit-loader').remove();
                        if (known == false) {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Alert!',
                                html: `<p>${response.message}</p><p>Total amount might be conflict so please validate it.</p>`,
                                confirmButtonColor: '#34B6B3',
                                customClass: {
                                    title: 'my-custom-title',
                                    content: 'my-custom-content'
                                }
                            });
                        }else{
                            Swal.fire({
                                position: "top-end",
                                text: response.message,
                                showConfirmButton: false,
                                timer: 2000
                            });
                        }
                        known = response.known;
                        $input.siblings('.display-data').removeClass('d-none');
                    },
                    error: function(xhr) {
                        $('.edit-loader').remove();
                        $input.siblings('.display-data').removeClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: xhr.responseText,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                });
            });
            
            jQuery(document).on('click', '#screenMode', function(){
                if(jQuery(this).text() == 'fullscreen'){
                    jQuery(this).text('fullscreen_exit');
                    jQuery('.pat-list').addClass('d-none');
                    jQuery('.preview-box').addClass('d-none');
                    jQuery('.doc-detail').addClass('col-sm-12');
                }else{
                    jQuery(this).text('fullscreen');
                    jQuery('.pat-list').removeClass('d-none');
                    jQuery('.preview-box').removeClass('d-none');
                    jQuery('.doc-detail').removeClass('col-sm-12');
                }
            });
            
            /* Settings */
            $('#settings').click(function () {
                $('#setting-screen').removeClass('d-none');
                $('#chatbot-screen').addClass('d-none');
                $('.menu__item').removeClass('menu__item--active');
                $(this).addClass('menu__item--active');
            });
            // Close chatbot screen
            $('.close-setting').click(function () {
                $('#setting-screen').addClass('d-none');
                $('.menu__item').removeClass('menu__item--active');
                $('#home').addClass('menu__item--active');
            });
            // Send message
            $('#save-settings').click(function () {
                $.ajax({
                    url: "{{ route('save.settings') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        GEN_CUSTOMER_ID: jQuery('#customer-id').val(),
                        GEN_PROJECT_ID: jQuery('#co-pilot').val(),
                        QUERY: jQuery('#query').val(),
                        STAGE: jQuery('#stage').val(),
                    },
                    success: function (response) {
                        Swal.fire({
                            position: "top-end",
                            text: 'Settings updated successfully!',
                            showConfirmButton: false,
                            timer: 2000
                        });
                        $('#setting-screen').addClass('d-none');
                        $('.menu__item').removeClass('menu__item--active');
                        $('#home').addClass('menu__item--active');
                    },
                    error: function (xhr) {
                        Swal.fire({
                            position: "top-end",
                            text: 'Something went wrong. Please try again later!',
                            showConfirmButton: false,
                            timer: 2000
                        });
                    },
                });
            });
        });
    </script>
@endpush