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

@section('content')
    <main class="container-fluid">
        <div class="row align-items-center">
            <div class="col-sm-3">
                <div class="col-sm-10 pl-0">
                    <a href="/dashboard">
                        <img src="{{env('AUTH_SERVER_URL')}}/public/images/MedX-Logo.png" width="75%" alt="Med-X Logo">
                    </a>
                </div>
            </div>
            <div class="col-sm-9">
                <div class="mt-0 d-flex justify-content-between">
                    <div class="dynamic-title pt-1">
                        <h4 class="secondary-color">Prior Authorization</h4>
                    </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>
        <div class="row">
            <div class="col-sm-3">
                <div class="input-group mt-3">
                    <input type="text" class="form-control" id="searchPatient" placeholder="Search Patient" aria-label="Search Patient">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <h3 class="font-weight-light mt-3 mb-0">Patient’s List</h3>
                <div class="user-list user-list-left"></div>
            </div>
            <div class="col-sm-7">
                <div class="center-box mt-3">
                    <p class="default-msg">Select a patient to get started!.</p>
                    <div class="loader-container preauth-loader d-none">
                        <div class="loader" id="loader"></div>
                    </div>
                    <div id="pre-auth-content" class="pre-auth-content d-none">
                        <style type="text/css"> * {margin:0; text-indent:0; }
                            .s1 { color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 11pt;margin-bottom: 0px; }
                            .s2 { color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 11pt; margin-bottom: 0px;}
                            .s3 { color: #00F; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: normal; text-decoration: underline; font-size: 11pt; }
                            .s4 { color: black; font-family:"Century Gothic", sans-serif; font-style: italic; font-weight: bold; text-decoration: none; font-size: 11pt;margin-bottom: 0px;  }
                            .s5 { color: black; font-family:"Century Gothic", sans-serif; font-style: italic; font-weight: normal; text-decoration: none; font-size: 11pt;margin-bottom: 0px;  }
                            .s7 { color: black; font-family:Arial, sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 11pt; }
                            .s8 { color: black; font-family:Arial, sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 9pt; }
                            .s9 { color: black; font-family:Arial, sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 9pt; }
                            .s10 { color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 12pt; }
                            .s11 { color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 6pt; }
                            .s13 { color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 12pt; }
                            li {display: block; }
                            #l1 {padding-left: 0pt; }
                            #l1> li>*:first-child:before {content: "☐ "; color: black; font-family:"Segoe UI Symbol", sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 11pt; }
                            li {display: block; }
                            #l2 {padding-left: 0pt;counter-reset: d1 4; }
                            #l2> li>*:first-child:before {counter-increment: d1; content: counter(d1, decimal)". "; color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 11pt; }
                            #l2> li:first-child>*:first-child:before {counter-increment: d1 0;  }
                            li {display: block; }
                            #l3 {padding-left: 0pt;counter-reset: e1 9; }
                            #l3> li>*:first-child:before {counter-increment: e1; content: counter(e1, decimal)". "; color: black; font-family:"Century Gothic", sans-serif; font-style: normal; font-weight: bold; text-decoration: none; font-size: 11pt; }
                            #l3> li:first-child>*:first-child:before {counter-increment: e1 0;  }
                            table, tbody {vertical-align: top; overflow: visible; }
                            .page-break {page-break-after: always;}

                        </style>
                        <table width="96%" style="margin-left:2%;margin-right:2%;margin-top:80px" cellspacing="0" cellpadding="5">
                            <tr>
                                <td colspan="2" style="border:1px solid;">
                                    <p class="s1" style="text-align: center;">Medicare Part D Prescription Coverage Request Form</p>
                                </td>
                            </tr>
                            <tr style="line-height:16pt">
                                <td colspan="2" style="border:1px solid;">
                                    <p style="text-align: center;margin-bottom: 0;"><a href="https://www.blueshieldca.com/medformulary2020" style=" color: black; font-family:&quot;Century Gothic&quot;, sans-serif; font-style: normal; font-weight: normal; text-decoration: none; font-size: 11pt;" target="_blank">View our formulary on line at </a><a href="https://www.blueshieldca.com/medformulary2020" class="s3" target="_blank">https://www.blueshieldca.com/medformulary2020</a></p>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="border:1px solid;">
                                    <p  class="s1" style="text-align: center;">Notice: Failure to complete this form in its entirety may result in delayed processing or an adverse<br>determination for insufficient information</p>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="border:1px solid;">
                                    <p class="s4" style="text-align: center;">Important Note: Expedited Decisions</p>
                                    <p class="s5" style="">If the standard decision time of 72 hours or less may seriously jeopardize the life or health of the enrollee or the enrollee’s ability to regain maximum function, an expedited (fast) decision can be requested.</p>
                                    <p class="s2" style=""><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp;CHECK THIS BOX IF A DECISION NEEDS TO BE GIVEN WITHIN 24 HOURS.</p>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" style="border:1px solid;">
                                    <p class="s1">Date of Request:</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" bgcolor="#F1F1F1">
                                    <p class="s1" style="text-align: center;">Physician Information</p>
                                </td>
                                <td style="border:1px solid;" bgcolor="#F1F1F1">
                                    <p class="s1" style="text-align: center;">Patient Information</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="width:50%;border:1px solid;">
                                    <p class="s2" style="margin:15px 0">Physician’s Name: <span class="practitioner-name"></span></p>
                                    <p class="s2" style="margin:15px 0"><input type="checkbox" class="pdfCheckbox" style="vertical-align: text-bottom;" />&nbsp;PCP; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp;Specialist:  <span class="specialist"></span></p>
                                    <p class="s2" style="margin:15px 0">Office<br>contact:<u> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u></p>
                                    <p class="s2" style="margin:15px 0">Phone#: <span>(  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )</span></p>
                                    <p class="s2" style="margin:15px 0">Facsimile #:  <span>(    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)</span></p>
                                </td>
                                <td style="width:50%;border:1px solid;">
                                    <p class="s2" style="margin:15px 0">Patient’s Name: <span class="patient-name"></span></p>
                                    <p class="s2" style="margin:15px 0">Patient’s Address: <span class="patient-address"></span></p>
                                    <p class="s2" style="margin:15px 0">Blue Shield ID#:</p>
                                    <p class="s2" style="margin:15px 0">Birthdate: <span class="birth-date"></span></p>
                                    <p class="s2" style="margin:15px 0">Patient’s height/weight:</p>
                                    <p class="s2" style="margin:15px 0">Drug Allergies:  <span class="deases"></span></p>
                                </td>
                            </tr>
                        </table>
                        <table width="96%" style="margin-left:2%;margin-right:2%;" cellspacing="0" cellpadding="5">
                            <tr>
                                <td style="border:1px solid; border-top:0;">
                                    <p class="s7" style="margin-bottom:15px;">DRUG REQUESTED:</p>
                                </td>
                                <td style="border:1px solid;width:15%; border-top:0;"">
                                    <p class="s7" style="margin-bottom:15px;">QUANTITY:</p>
                                </td>
                                <td style="border:1px solid; border-top:0;"">
                                    <p class="s7" style="margin-bottom:15px;">EXPECTED LENGTH OF THERAPY:</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid; border-top:0;"">
                                    <p class="s7" style="margin-bottom:15px;">STRENGTH AND ROUTE OF ADMINISTRATION:</p>
                                </td>
                                <td style="border:1px solid; border-top:0;" colspan="2">
                                    <p class="s7" style="margin-bottom:15px;">DIRECTIONS:</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;"" width="65%" colspan="2">
                                    <p class="s7" style="margin-bottom:0px;">DIAGNOSIS: Please list all diagnoses being treated with the requested drug and corresponding ICD-10 codes.</p>
                                    <p class="s8" style="margin-bottom:5px;">(<span class="s9">If the condition being treated with the requested drug is a symptom e.g. anorexia, weight loss, shortness of breath, chest pain, nausea, etc., provide the diagnosis causing the symptom(s) if known)</span></p>
                                    <span class="soapnote s2"></span>
                                </td>
                                <td style="border:1px solid;" width="35%">
                                    <p class="s7">ICD-10 CODE(S): <br><span class="icd"></span></p>
                                    <!--<p class="s7" style="margin-top:10px;">CPT CODE(S): <span class="cpt"></span></p>-->
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="2">
                                    <p class="s7" style="margin-bottom:30px;">OTHER RELAVENT DIAGNOSES:</p>
                                </td>
                                <td style="border:1px solid;">
                                    <p class="s7">ICD-10 CODE(S):</p>
                                </td>
                            </tr>
                        </table>
                        <table width="96%" style="margin-left:2%;margin-right:2%;" cellspacing="0" cellpadding="5">
                            <tr>
                                <td style="border:1px solid;" colspan="3">
                                    <p class="s10" style="text-align: center; margin:0; ">FAX form to: 1(888)697-8122</p>
                                </td>
                                <td style="border:1px solid;" colspan="2">
                                    <p class="s10" style="text-align: center; margin:0;">Pharmacy Services Phone #: 1(800)535-9481</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                    <p class="s11" style="font-size:10px;">This facsimile transmission may contain protected and privileged, highly confidential medical, Personal and Health Information (PHI) and/or legal information. The information is intended only for the use of the individual or entity named above.</p>
                                    <p class="s11" style="font-size:10px;">If you are not the intended recipient of this material, you may not use, publish, discuss, disseminate or otherwise distribute it. If you are not the intended recipient, or if you have received this transmission in error, please notify the sender immediately and <b>confidentially </b>destroy the information that faxed in error.</p>
                                    <p class="s11" style="font-size:10px;">Thank you for your help in maintaining appropriate confidentiality.</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                </td>
                            </tr>
                        </table>
                        <div class="page-break"></div>
                        <table width="96%" style="margin-left:2%;margin-right:2%; margin-top:80px" cellspacing="0">

                            <tr>
                                <td  style="border:1px solid; padding-bottom: 10px;" colspan="3">
                                    <p class="s1" style="padding-top: 6pt;margin-bottom:15px; padding-left: 5pt;">1. <span class="s2">Is this new therapy?   <input type="checkbox" class="pdfCheckbox" style="vertical-align: text-bottom;" />&nbsp;Yes   <input type="checkbox" class="pdfCheckbox" style="vertical-align: text-bottom;" />&nbsp;No. If no, please provide date therapy was started.</span></p>
                                    <p class="s1" style="padding-top: 2pt;padding-left: 5pt;">Type of coverage <span class="s13">determination </span>requested <i>(please check the appropriate box)</i></p>
                                    <p class="s2" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" checked style="vertical-align:  text-bottom;" />&nbsp; Prior Authorization</p>
                                    <p class="s2" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" class="pdfCheckbox" class="pdfCheckbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Request for a drug that is not on the plan’s list of covered drugs (formulary exception)</p>
                                    <p class="s2" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" class="pdfCheckbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Request an exception to the requirement that another drug is tried before receiving the drug prescribed (formulary exception).</p>
                                    <p class="s2" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Request an exception to the plan’s limit on the number of pills (quantity limit) that can be received at one time (formulary exception).</p>
                                    <p class="s2" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Request to lower the copayment for a drug that has been prescribed (tiering exception).</p>
                                    
                        
                                    <p style="padding-top: 2pt;"><br/></p>
                                    <p class="s1" style="padding-left: 5pt;">2. <span class="s2">Check the box that best describes the location where the drug will be administered:</span></p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Patient’s home or assisted living facilities</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Long Term Care Facilities (LTC)/Skilled Nursing Facilities (SNF)</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Ambulatory Infusion Center (infusion center supplies the drug)</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Ambulatory Infusion Center (retail/outpatient pharmacy supplies the drug)</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Office administered (office supplies the drug)</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Office administered (retail/outpatient pharmacy supplies the drug)</p>
                                    <p class="s2" style="padding-top: 5pt;padding-left: 20pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;" />&nbsp; Other            (explain):            <u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid" colspan="3" bgcolor="#DBDBDB">
                                    <p class="s1" style="padding-left: 4pt;">DRUG <span class="s13">HISTORY</span>: (for treatment of the condition(s) requiring the requested drug)</p>
                                </td>
                            </tr>
                            <tr style="text-align: center;">
                                <td style="border:1px solid">
                                    <p class="s1" style="padding-top: 6pt;">DRUGS TRIED</p>
                                    <p class="s2" style="padding: 6pt;">(if quantity limit is an issue, list unit dose/total daily dose tried)</p>
                                </td>
                                <td style="border:1px solid">
                                    <p class="s1" style="padding-top: 6pt;text-align: center;">DATES of Drug Trials</p>
                                </td>
                                <td style="border:1px solid">
                                    <p class="s1" style="padding-top: 6pt;">RESULTS of previous drug trials</p>
                                    <p class="s1" style="padding-top: 4pt;">FAILURE vs INTOLERANCE</p>
                                    <p class="s1" style="padding-top: 4pt;">(explain)</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                                <td style="border:1px solid">
                                    <p><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid" colspan="3">
                                    <p class="s1" style="padding-top: 6pt;padding-left: 5pt;">3. <span class="s2">What is the current drug regimen for the condition?</span></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style=" margin:0 10px;"><br/></p>
                                    
                                </td>
                            </tr>
                        </table>
                        <table width="96%" style="margin-left:2%;margin-right:2%;" cellspacing="0" cellpadding="5">
                            <tr>
                                <td style="border:1px solid;" colspan="3">
                                    <p class="s10" style="text-align: center; margin:0; ">FAX form to: 1(888)697-8122</p>
                                </td>
                                <td style="border:1px solid;" colspan="2">
                                    <p class="s10" style="text-align: center; margin:0;">Pharmacy Services Phone #: 1(800)535-9481</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                    <p class="s11" style="font-size:10px;">This facsimile transmission may contain protected and privileged, highly confidential medical, Personal and Health Information (PHI) and/or legal information. The information is intended only for the use of the individual or entity named above.</p>
                                    <p class="s11" style="font-size:10px;">If you are not the intended recipient of this material, you may not use, publish, discuss, disseminate or otherwise distribute it. If you are not the intended recipient, or if you have received this transmission in error, please notify the sender immediately and <b>confidentially </b>destroy the information that faxed in error.</p>
                                    <p class="s11" style="font-size:10px;">Thank you for your help in maintaining appropriate confidentiality.</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                </td>
                            </tr>
                        </table>
                        <p style="text-indent: 0pt;text-align: left;">
                        </p>
                        <div class="page-break"></div>
                        <table width="96%" style="margin-left:2%;margin-right:2%; margin-top:80px" cellspacing="0">
                            <tr>
                                <td style="border:1px solid;" bgcolor="#DBDBDB">
                                    <p class="s10" style="padding:0px 5pt; margin:0; ">DRUG SAFETY</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid; margin-bottom:10px;">
                                    <p class="s1" style="padding-top: 6px;padding-left: 5px;">4. <span class="s2">Any <b>FDA NOTED CONTRAINDICATIONS </b>to the requested drug? &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO</span></p>
                                    <p class="s1" style="padding-top: 6px;padding-left: 5px;">5. <span class="s2">Any concern for a <b>DRUG INTERACTION </b>with the addition of the requested drug to the enrollee’s <br>&nbsp;&nbsp;&nbsp;&nbsp;current drug regimen? &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO</span></p>
                                    <p class="s2" style="padding-top: 6px;padding-left: 18px;">If the answer to either of the questions noted above is yes, please 1) explain issue, 2) discuss the benefits vs potential risks despite the noted concern, and 3) monitoring plan to ensure safety</p>
                                    <p style="border-bottom:1px solid; margin:0 10px; margin-left: 18px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px; margin-left: 18px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px; margin-left: 18px;"><br/></p>
                                    <p style=" margin:0 10px;"><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1pt solid;" bgcolor="#DBDBDB">
                                    <p class="s10" style="padding:0px 5pt; margin:0; ">HIGH RISK MANAGEMENT OF DRUGS IN THE ELDERLY</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1pt solid;">
                                    <p class="s1" style="padding: 5pt ;">6. <span class="s2">If the enrollee is over the age of 65, do you feel that the benefits of treatment with the requested drug outweigh the potential risks in this elderly patient? &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO</span></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1pt solid" bgcolor="#DBDBDB">
                                    <p class="s10" style="padding:0px 5pt; margin:0; ">OPIOIDS – (please complete the following questions if the requested drug is an opioid)</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;">
                                    <p class="s1" style="padding: 5pt ;">7. <span class="s2">What is the daily cumulative Morphine Equivalent Dose </span>(MED)<span class="s2" style="margin-right:20px;">?    </span>mg/day</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid; padding-bottom:30px;">
                                    <p class="s1" style="padding: 5pt ;">8. <span class="s2">Are you aware of other opioid prescribers for this enrollee?   &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO <br>If so, please explain.</span></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;">
                                            <p class="s1" style="padding: 5pt ;">9. <span class="s2">Is the stated daily MED dose noted medically necessary?   &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO</span></p>
                                            <p class="s1" style="padding: 5pt ;">10. <span class="s2">Would a lower total daily MED dose be insufficient to control the enrollee’s pain?   &nbsp; <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;YES   &nbsp;&nbsp;  <input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;NO</span></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid; text-align:center;" bgcolor="#E7E6E6">
                                <p class="s10" style="padding:0px; margin:0; font-size:15px;">FORMULARY and TIERING EXCEPTION requests cannot be processed without a prescriber’s supporting<br>
                                statement. PRIOR AUTHORIZATION requests may require supporting information.</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid" >
                                    <p class="s1" style="padding-top: 2pt;padding-left: 5pt;">Prescriber’s Rationale for request:</p>
                                    <p class="s1" style="padding-top: 6pt;padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;Alternate drug(s) contraindicated or previously tried, but with adverse outcome, e.g., toxicity, allergy, or therapeutic failure <span class="s2">[Specify below if not already noted in the DRUG HISTORY section earlier on the form: (1) Drug(s) tried and results of drug trial(s) (2) if adverse outcome, list drug(s) and adverse outcome for each, (3) if therapeutic failure, list maximum dose and length of therapy for drug(s) trialed, (4) if contraindication(s), please list specific reason why preferred drug(s)/other formulary drug(s) are contraindicated]</span></p>
                                    <p class="s1" style="padding-top: 6pt;padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;Patient is stable on current drug(s); high risk of significant adverse clinical outcome with medication change <span class="s2">A specific explanation of any anticipated significant adverse clinical outcome and why a significant adverse outcome would be expected is required – e.g. the condition has been difficult to control (many drugs tried, multiple drugs required to control condition), the patient had a significant adverse outcome when the condition was not controlled previously (e.g. hospitalization or frequent acute medical visits, heart attack, stroke, falls, significant limitation of functional status, undue pain and suffering),etc.</span></p>
                                </td>
                            </tr>
                        </table>
                        <table width="96%" style="margin-left:2%;margin-right:2%;" cellspacing="0" cellpadding="5">
                            <tr>
                                <td style="border:1px solid;" colspan="3">
                                    <p class="s10" style="text-align: center; margin:0; ">FAX form to: 1(888)697-8122</p>
                                </td>
                                <td style="border:1px solid;" colspan="2">
                                    <p class="s10" style="text-align: center; margin:0;">Pharmacy Services Phone #: 1(800)535-9481</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                    <p class="s11" style="font-size:10px;">This facsimile transmission may contain protected and privileged, highly confidential medical, Personal and Health Information (PHI) and/or legal information. The information is intended only for the use of the individual or entity named above.</p>
                                    <p class="s11" style="font-size:10px;">If you are not the intended recipient of this material, you may not use, publish, discuss, disseminate or otherwise distribute it. If you are not the intended recipient, or if you have received this transmission in error, please notify the sender immediately and <b>confidentially </b>destroy the information that faxed in error.</p>
                                    <p class="s11" style="font-size:10px;">Thank you for your help in maintaining appropriate confidentiality.</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                </td>
                            </tr>
                        </table>
                        <p style="text-indent: 0pt;text-align: left;">
                        </p>
                        <div class="page-break"></div>
                        <table width="96%" style="margin-left:2%;margin-right:2%; margin-top:80px"  cellspacing="0">
                            <tr>
                                <td style="border:1px solid" colspan="2">
                                    <p class="s1" style="padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;Medical need for different dosage form and/or higher dosage <span class="s2">[Specify below: (1) Dosage form(s) and/or dosage(s) tried and outcome of drug trial(s); (2) explain medical reason (3) include why less frequent dosing with a higher strength is not an option – if a higher strength exists]</span></p>
                                    <p class="s1" style="padding-top: 6pt;padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;Request for formulary tier exception <span class="s2">Specify below if not noted in the DRUG HISTORY section earlier on the form: (1) formulary or preferred drug(s) tried and results of drug trial(s) (2) if adverse outcome, list drug(s) and adverse outcome for each, (3) if therapeutic failure/not as effective as requested drug, list maximum dose and length of therapy for drug(s) trialed, (4) if contraindication(s), please list specific reason why preferred drug(s)/other formulary drug(s) are contraindicated]</span></p>
                                    <p class="s1" style="padding-top: 6pt;padding-left: 5pt;"><input type="checkbox" class="pdfCheckbox" style="vertical-align:  text-bottom;"/>&nbsp;Other <span class="s2">(explain below)</span></p>
                                    <p class="s1" style="padding-top: 4pt;padding-left: 5pt;">Required Explanation</p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style="border-bottom:1px solid; margin:0 10px;"><br/></p>
                                    <p style=" margin:0 10px;"><br/></p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1pt solid">
                                    <p class="s1" style="padding-left: 5pt;margin-bottom:20px">Provider Signature:</p>
                                </td>
                                <td style="border:1pt solid">
                                    <p class="s1" style="padding-left: 5pt;">Date:</p>
                                </td>
                            </tr>
                        </table>
                        <table width="96%" style="margin-left:2%;margin-right:2%;" cellspacing="0" cellpadding="5">
                            <tr>
                                <td style="border:1px solid;" colspan="3">
                                    <p class="s10" style="text-align: center; margin:0; ">FAX form to: 1(888)697-8122</p>
                                </td>
                                <td style="border:1px solid;" colspan="2">
                                    <p class="s10" style="text-align: center; margin:0;">Pharmacy Services Phone #: 1(800)535-9481</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                    <p class="s11" style="font-size:10px;">This facsimile transmission may contain protected and privileged, highly confidential medical, Personal and Health Information (PHI) and/or legal information. The information is intended only for the use of the individual or entity named above.</p>
                                    <p class="s11" style="font-size:10px;">If you are not the intended recipient of this material, you may not use, publish, discuss, disseminate or otherwise distribute it. If you are not the intended recipient, or if you have received this transmission in error, please notify the sender immediately and <b>confidentially </b>destroy the information that faxed in error.</p>
                                    <p class="s11" style="font-size:10px;">Thank you for your help in maintaining appropriate confidentiality.</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="border:1px solid;" colspan="5">
                                </td>
                            </tr>
                        </table>
                        <p style="text-indent: 0pt;text-align: left;">
                        </p>
                    </div>
                    <div class="downloadBtn d-none">
                        <button id="downloadPdfBtn" class="btn btn-success primary-bg-color">Download PDF</button>
                        <button id="downloadPdfBunch" class="btn btn-success d-none primary-bg-color ml-3">Download All</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>
        <!-- AI Content Generation Confirm Modal -->
        <div class="modal" id="notes" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog modal-md modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Generate Prior Auth Form</h5>
                    </div>
                    <div class="patient-loading"></div>
                    <form id="notesForm">
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <label for="PriorAuthType" class="col-form-label">Prior Auth Type</label>
                                        <select id="PriorAuthType" class="form-control" required>
                                            <option value="" disabled>Please Select</option>
                                            <option value="Dental Template" selected>Dental Template</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="hisotry" class="row">
                                <div class="col-md-6">
                                    <label for="hisotryData" class="col-form-label">Select SOAP(s)</label>
                                    <div id="hisotryData"></div>
                                </div>
                                <div class="col-md-6">
                                    <label for="reportData" class="col-form-label">Select Report(s)</label>
                                    <div id="reportData"></div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-center note-footer">
                            <button type="submit" class="btn btn-outline-primary">Next</button>
                            <button type="button" class="btn btn-outline-danger note-modal-close" data-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>
@endsection

@push('scripts')
    <script>
        $(document).ready(function() {
            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 });
                        break;
                    case 'compact':
                        formattedDate = dateObj.toISOString().slice(8, 10) +
                           dateObj.toISOString().slice(5, 7) +
                           dateObj.toISOString().slice(2, 4) +
                           dateObj.toISOString().slice(11, 13) +
                           dateObj.toISOString().slice(14, 16) +
                           dateObj.toISOString().slice(17, 19);
                    default:
                        formattedDate = dateObj.toISOString();
                        break;
                }
                return formattedDate;
            }
            
            const md = window.markdownit();
            $('.pdfCheckbox').click(function() {
                const checkbox = this; // Reference to the clicked checkbox
                if ($(checkbox).is(':checked')) {
                    checkbox.setAttribute('checked', 'true'); // Sets the checked attribute
                } else {
                    checkbox.removeAttribute('checked'); // Removes the checked attribute
                }
            });

            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            $('#patientId').select2({
                placeholder: "Select Patient",
                allowClear: false
            });
            
            function displayPatients(patientList) {
                const historyList = $('.user-list-left');
                historyList.empty();
                $.each(patientList, function(index, patient) {
                    $('.user-list-left').append(`
                        <div class="right-bottom-border pre-auth-appointment-list" data-patientId="${patient.patientId}" data-patient-name="${patient.patientName}" data-address="${patient.address}" data-address-type="${patient.addressType}" data-birth-date="${patient.birthDate}" data-deceased-boolean="${patient.deceasedBoolean}" data-gender="${patient.gender}" data-telecom="${patient.telecom}" data-telecom-use="${patient.telecomUse}">
                            <span id="appointment" class="m-0"><span>${patient.patientName}</span></span>
                        </div>
                    `);
                });
            }
            
            let patients = [];
            function getPatientsList() {
                const formData = new FormData();
                // formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('practitioner', "practitioner");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/patients",
                    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>
                `);
                $.ajax(settings).done(response => {
                    if(response.data.length > 0){
                        patients = response.data;
                        displayPatients(response.data);
                    }
                }).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);
                });
            }
            getPatientsList();
            
            jQuery('#searchPatient').keyup(function() {
                var searchInput = jQuery(this).val().toLowerCase();
                var filteredPatients = patients.filter(function(patient) {
                    return patient.patientName.toLowerCase().includes(searchInput);
                });
                if (filteredPatients.length > 0) {
                    displayPatients(filteredPatients)
                } else {
                    jQuery('.user-list-left').html('<p>No patients found</p>');
                }
            });
            
            function displayHistoryList(historyData) {
                const historyList = $('.user-list-left');
                historyList.empty();
                if(historyData.length > 0){
                    var cnt = 1;
                    historyData.forEach(item => {
                        if(item.comment != '' && cnt <= 10){
                            $('.user-list-left').append(`
                                <div class="right-bottom-border pre-auth-appointment-list" data-appointmentId="${item.appointmentId}" data-encounterId="${item.encounterId}" data-soapnote="${encodeURIComponent(item.comment)}">
                                    <span id="appointment" class="m-0"><span>${formatDateTime(item.timeSlot, {format:'full',  locale:'en-US', hour12:true})}</span></span>
                                </div>
                            `);
                            cnt++;
                        }
                    });
                }else{
                    $('.user-list-left').html('<p class="pt-2">Appointment history not available.</p>');
                }
            }
            
            function getAllReports(patientId){
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', patientId);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/patient/reports",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#reportData').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    jQuery('#reportData').html('');
                    if(response.data.length > 0){
                        var cnt = 1;
                        response.data.forEach(reports => {
                            reports.report.forEach(item => {
                                const reportTime = formatDateTime(reports.date, {format:'full',  locale:'en-US', hour12:true});
                                if(item.reportSummary != '' && cnt <= 10){
                                    jQuery('#reportData').append(`
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="reportHistory[]" value="${encodeURIComponent(reports.reportSummary)}" data-url="${item.reportURL}" id="reportSummary-${reports.date}">
                                            <label class="form-check-label fw-500" for="reportSummary-${reports.date}">${reportTime}</label>
                                        </div>
                                    `);
                                    cnt++;
                                }
                            });
                        });
                    }else{
                        jQuery('#reportData').html('');
                        jQuery('#reportData').append('<p class="pt-2">Reports has not been uploaded yet.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#reportData').html('');
                    jQuery('#reportData').html('<p>Error loading reports. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function displayHistoryList(historyData) {
                const historyList = $('#hisotryData');
                historyList.empty();
                if(historyData.length > 0){
                    var cnt = 1;
                    var noHistory = false;
                    historyData.forEach(item => {
                        if(item.comment != '' && cnt <= 10){
                            historyList.append(`
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="soapHistory[]" value="${encodeURIComponent(item.comment)}" id="soapSummary-${item.timeSlot}-${cnt}">
                                    <label class="form-check-label fw-500" for="soapSummary-${item.timeSlot}-${cnt}">${formatDateTime(item.timeSlot, {format:'MsD2Yn',  locale:'en-US'})}</label>
                                </div>
                            `);
                            cnt++;
                            noHistory = true;
                        }
                    });
                    if(!noHistory){
                        historyList.append('<p class="pt-2">Previous medical history is not available.</p>'); 
                    }
                }else{
                    historyList.append('<p class="pt-2">Appointment history not available.</p>');
                }
            }
            
            function getPatientHistory(patientId){
                const practitionerId = "{{ session('PractitionerId') }}";
                const formData = new FormData();
                formData.append('timezone', timeZone);
                const settings = {
                    url: `{{env('API_URL')}}{{session('currentEHR')}}/patient/history/practitioner/${patientId}`,
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#hisotryData').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    displayHistoryList(response.data);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#hisotryData').html('<p>Error loading appointment history. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            let reportURLArray = [];
            jQuery(document).on('click', '.pre-auth-appointment-list', function(){
                jQuery('.pre-auth-appointment-list').removeClass('pre-auth-appointment-list-selected');
                jQuery(this).addClass('pre-auth-appointment-list-selected');
                jQuery('.practitioner-name').text("{{session('PractitionerName')}}");
                jQuery('.specialist').text("{{session('suffix')}}");
                jQuery('.patient-name').text($(this).attr('data-patient-name'));
                jQuery('.patient-address').text($(this).attr('data-address'));
                jQuery('.birth-date').text($(this).attr('data-birth-date'));
                jQuery('.deases').text($(this).attr('data-deceased-boolean') == 'false' ? 'No' : 'Yes');
                jQuery('.icd').html('');
                jQuery('.cpt').html('');
                jQuery('.soapnote').html('');
                getAllReports($(this).attr('data-patientid'));
                getPatientHistory($(this).attr('data-patientid'));
                jQuery('.default-msg').addClass('d-none');
                jQuery('#pre-auth-content').addClass('d-none');
                jQuery('.downloadBtn').addClass('d-none');
                jQuery('#notes').modal('show');
                reportURLArray = [];
                
                // let soapnote = decodeURIComponent(jQuery('.pre-auth-appointment-list-selected').attr('data-soapnote'));
                // soapnote = soapnote.replace(/\\n/g, '\n');
                // soapnote = soapnote.replace(/^[A-Za-z]{3} \d{1,2}, \d{4}:\n\n/, '');
                // soapnote = soapnote.replace(/(SOAP Note:|Subjective:|Objective:|Assessment:|Plan:)/g, '**$1**');
                // soapnote = soapnote.replace(/Suggested ICD-10 Codes:[\s\S]*?(?=Suggested CPT Codes:|$)/, '');
                // soapnote = soapnote.replace(/Suggested CPT Codes:[\s\S]*?(?=Note:|$)/, '');
                // soapnote = soapnote.replace(/Note:.*?CPT[\s\S]*?$/, '');
                // const soapSummary = md.render(soapnote);
                // jQuery('.soapnote').html(soapSummary);
                
                // if(jQuery('.pre-auth-appointment-list-selected').attr('data-encounterid') != "" && jQuery('.pre-auth-appointment-list-selected').attr('data-encounterid') != "null"){
                //     $.ajax({
                //         url: "{{env('API_URL')}}{{session('currentEHR')}}/get/icd-cpt/"+jQuery('.pre-auth-appointment-list-selected').attr('data-encounterid'),
                //         type: 'POST',
                //         data: { _token: '{{ csrf_token() }}' },
                //         headers: {
                //             "Authorization": "Bearer " + "{{ session('accessToken') }}"
                //         },
                //         success: function (response) {
                //             $.each(response.data.icdCodes, function(index, icdCode) {
                //                 jQuery('.icd').append(icdCode.code + '<br>');
                //                 // jQuery('.codes').append(icdCode.code + '(' + icdCode.display + ')' + '<br>');
                //             });
                //             $.each(response.data.cptCodes, function(index, cptCode) {
                //                 $('.cpt').append(cptCode.code + '<br>');
                //             });
                //         },
                //         error: function (xhr) {
                //             Swal.fire({
                //                 position: "top-end",
                //                 text: xhr.responseText.message,
                //                 showConfirmButton: false,
                //                 timer: 2000
                //             });
                //         }
                //     });
                // }
                // jQuery('.default-msg').addClass('d-none');
                // jQuery('#pre-auth-content').removeClass('d-none');
                // jQuery('#pre-auth-content').append(`<p><b>Appointment</b>: ${jQuery(this).attr('data-appointmentid')}</p>`);
            });
            
            jQuery(document).on('click', '.note-modal-close', function(){
                jQuery('.pre-auth-appointment-list').removeClass('pre-auth-appointment-list-selected');
                jQuery('.default-msg').removeClass('d-none');
                jQuery('.preauth-loader').addClass('d-none');
                jQuery('#pre-auth-content').addClass('d-none');
                jQuery('.downloadBtn').addClass('d-none');
                jQuery('#downloadPdfBunch').addClass('d-none');
            });
            
            jQuery('#notesForm').on('submit', function(e) {
                e.preventDefault();
                if (jQuery('#PriorAuthType').val() == '') {
                    jQuery('#PriorAuthType').focus();
                    return false;
                }
                if($('input[name="soapHistory[]"]:checked').length === 0 && $('input[name="reportHistory[]"]:checked').length === 0){
                    jQuery('#notes').modal('hide');
                    jQuery('#pre-auth-content').removeClass('d-none');
                    jQuery('.downloadBtn').removeClass('d-none');
                    jQuery('#downloadPdfBunch').addClass('d-none');
                } else {
                    var soapSelected = true;
                    var reportSelected = true;
                    if ($('input[name="soapHistory[]"]:checked').length === 0) {
                        jQuery('input[name="soapHistory[]"]').focus();
                        soapSelected = false;
                    } if ($('input[name="reportHistory[]"]:checked').length === 0) {
                        jQuery('input[name="reportHistory[]"]').focus();
                        reportSelected = false;
                    }
                    jQuery('#notes').modal('hide');
                    if(soapSelected || reportSelected){
                        jQuery('.preauth-loader').removeClass('d-none');
                        generateNote();
                    }else{
                        jQuery('#pre-auth-content').removeClass('d-none');
                        jQuery('.downloadBtn').removeClass('d-none');
                        jQuery('#downloadPdfBunch').addClass('d-none');
                    }
                }
            });
            
            function generateNote() {
                var selectedText = $('#generateType option:selected').text();
                let soapHistory = $('input[name="soapHistory[]"]:checked')
                    .map(function() {
                        return decodeURIComponent($(this).val());
                    })
                    .get()
                    .join('\n\n');
                let reportHistory = $('input[name="reportHistory[]"]:checked')
                    .map(function() {
                        return decodeURIComponent($(this).val());
                    })
                    .get()
                    .join('\n\n');
                reportURLArray = $('input[name="reportHistory[]"]:checked')
                    .map(function() {
                        return $(this).attr('data-url');
                    })
                    .get();
                const reportCount = $('input[name="reportHistory[]"]:checked').length;
                console.log(reportCount);
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', $('.pre-auth-appointment-list-selected').attr('data-patientid'));
                formData.append('soapSummaries', soapHistory);
                formData.append('reportSummaries', reportHistory);
                formData.append('noteType', 'PREAUTH');
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/generate/pre-auth-note",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    // let soapnote = response.data.generatedNote;
                    // soapnote = soapnote.replace(/\\n/g, '\n');
                    // soapnote = soapnote.replace(/^[A-Za-z]{3} \d{1,2}, \d{4}:\n\n/, '');
                    // soapnote = soapnote.replace(/(SOAP Note:|Subjective:|Objective:|Assessment:|Plan:)/g, '**$1**');
                    // soapnote = soapnote.replace(/Suggested ICD-10 Codes:[\s\S]*?(?=Suggested CPT Codes:|$)/, '');
                    // soapnote = soapnote.replace(/Suggested CPT Codes:[\s\S]*?(?=Note:|$)/, '');
                    // soapnote = soapnote.replace(/Note:.*?CPT[\s\S]*?$/, '');
                    // const soapSummary = md.render(soapnote);
                    jQuery('.soapnote').html(`<p>${response.data.generatedNote}</p>`);
                    $.each(response.data.icdCodes, function(index, icdCode) {
                        // jQuery('.icd').append(icdCode.code + '<br>');
                        jQuery('.icd').append(icdCode.code + '(' + icdCode.description + ')' + '<br>');
                    });
                    $.each(response.data.cptCodes, function(index, cptCode) {
                        // $('.cpt').append(cptCode.code + '<br>');
                    });
                    $('#notesForm').trigger('reset');
                    $('#PriorAuthType').val('Dental Template');
                    jQuery('.default-msg').addClass('d-none');
                    jQuery('.preauth-loader').addClass('d-none');
                    jQuery('#pre-auth-content').removeClass('d-none');
                    jQuery('.downloadBtn').removeClass('d-none');
                    if(reportCount > 0) {
                        jQuery('#downloadPdfBunch').removeClass('d-none');
                    }else{
                        jQuery('#downloadPdfBunch').addClass('d-none');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('#notesForm').trigger('reset');
                    $('#PriorAuthType').val('Dental Template');
                    jQuery('.default-msg').addClass('d-none');
                    jQuery('.preauth-loader').addClass('d-none');
                    jQuery('#pre-auth-content').removeClass('d-none');
                    jQuery('.downloadBtn').removeClass('d-none');
                    if(reportCount > 0) {
                        jQuery('#downloadPdfBunch').removeClass('d-none');
                    }else{
                        jQuery('#downloadPdfBunch').addClass('d-none');
                    }
                    // Swal.fire({
                    //     position: "top-end",
                    //     text: "Error while generating note. Please try again later.",
                    //     showConfirmButton: false,
                    //     timer: 2000
                    // });
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            /* 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);
                });
            });
            
            $('#downloadPdfBtn').on('click', function() {
                const content = $('#pre-auth-content').html();
                $.ajax({
                    url: "{{env('APP_URL')}}/download-pdf",
                    type: 'POST',
                    data: { content },
                    headers: { 
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    },
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function (response) {
                        const blob = new Blob([response], { type: 'application/pdf' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'Pre Auth.pdf';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        Swal.fire({
                            position: "top-end",
                            text: 'Prior Authorization PDF download successfully.',
                            showConfirmButton: false,
                            timer: 2000
                        });
                    },
                    error: function (xhr) {
                        Swal.fire({
                            position: "top-end",
                            text: xhr.responseText.message,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                });
            });
            
            $('#downloadPdfBunch').on('click', function() {
                jQuery('.loading').removeClass('d-none');
                const content = $('#pre-auth-content').html();
                $.ajax({
                    url: "{{env('APP_URL')}}/download-zip",
                    type: 'POST',
                    data: { content: content, files: [...reportURLArray], patientId: $('.pre-auth-appointment-list-selected').attr('data-patientid'), timezone: timeZone },
                    headers: { 
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    },
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function (response) {
                        const blob = new Blob([response], { type: 'application/zip' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'eligibility-bunch.zip';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        Swal.fire({
                            position: "top-end",
                            text: 'Prior Authorization PDF download successfully.',
                            showConfirmButton: false,
                            timer: 2000
                        });
                        jQuery('.loading').addClass('d-none');
                    },
                    error: function (xhr) {
                        jQuery('.loading').addClass('d-none');
                        Swal.fire({
                            position: "top-end",
                            text: xhr.responseText.message,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                });
            });
        });
    </script>
@endpush