{% set userData = app.session.get('userData') %}
{% set absUrl = app.request.getSchemeAndHttpHost() ~ app.request.baseUrl|replace({'/app_dev.php': ''}) %}
<style>
    {% if form.action.vars.value == 'n' %}
        .payer_type_choice_financing{
            display: none;
        }
    {% endif %}

    form,select, label{
        font-size: 12px;
    }
    input[type=text] {
        font-size: 13px;
    }
    label {
        text-align: left;
    }
    .dropdown-pane {
        right: -260px!important;
        top: 3em!important;
    }
    .dropdown-pane ul {
        margin-left: 1em!important;
    }
    .visible{
        visibility: visible!important;
    }
    .select2 {
        width: 100%!important;
    }
    .add_serial_input_btn, .remove_serial_input_btn {
        min-width: unset;
        height: unset;
        margin-bottom: 0!important;
    }
    .select2-selection{
        min-height: unset!important;
    }
</style>
<form method="POST" id="form-patientBilling-void">
    <div style="display: inline">
        <h5>{{ page_title }}</h5>
        {#{% if form.action.vars.value|default('') == 'u' and patientBilling.billingStatus|default('') != 'Void' and (userData.type == 'Super Admin' or 'Admin Patient Billing Void' in userData.accesses)  %}
            <input type="hidden" value="{{ form.id.vars.value|default('') }}" name="patientBilling[id]"/>
            <input type="hidden" value="{{ form.action.vars.value }}" name="patientBilling[action]"/>
        {% endif %}#}
    </div>
</form>
<form method="POST" id="form-patientBilling" enctype="multipart/form-data">
    <div id="flash-messages-content-modal"></div>
    <div class="row max-width-initial">
        <div class="large-12 columns" style="margin-bottom: 10px;">
            <h5 class="subheader">Basic information</h5>
            {#<p class="form-hint-text">Enter basic information below</p>#}
            <div style="width: 100%">
                <div style="width: 24%; float: left; text-align: left; margin-right:7px;">
                    <div class="row">
                        <div class="large-5 columns text-right">
                            {{ form_label(form.billing_date) }}
                        </div>
                        <div class="large-7 columns">
                            {{ form_widget(form.billing_date) }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-5 columns text-right">
                            {{ form_label(form.due_date) }}
                        </div>
                        <div class="large-7 columns">
                            {{ form_widget(form.due_date) }}
                        </div>
                    </div>
                    {% if form.action.vars.value != 'u' and patientBilling.prevSysInvoiceNo|default('') == '' %}
                        <div class="row {{ form.action.vars.value != 'u' and patientBilling.prevSysInvoiceNo|default('') == '' ? '' : 'hide' }}">
                            <div class="large-5 columns text-right">
                                {{ form_label(form.invoice_no) }}
                            </div>
                            <div class="large-7 columns">
                                {{ form_widget(form.invoice_no) }}
                            </div>
                        </div>
                    {% else %}
                        <div class="row {{ form.action.vars.value == 'u' ? '' : 'hide' }}">
                            <div class="large-5 columns text-right">
                                {{ form_label(form.invoice_no) }}
                            </div>
                            <div class="large-7 columns">
                                <input type="text" name="patientBilling[invoice_no]" readonly value="{{ patientBilling.invoiceNo ? patientBilling.invoiceNo : patientBilling.prevSysInvoiceNo }}">
                            </div>
                        </div>
                    {% endif %}
                    {#<div class="row {{ form.action.vars.value != 'u' and patientBilling.prevSysInvoiceNo|default('') == '' ? '' : 'hide' }}">
                        <div class="large-5 columns text-right">
                            {{ form_label(form.invoice_no) }}
                        </div>
                        <div class="large-7 columns">
                            {{ form_widget(form.invoice_no) }}
                        </div>
                    </div>
                    <div class="row {{ form.action.vars.value == 'u' ? '' : 'hide' }}">
                        <div class="large-5 columns text-right">
                            {{ form_label(form.invoice_no) }}
                        </div>
                        <div class="large-7 columns">
                            <input type="text" name="patientBilling[invoice_no]" readonly value="{{ patientBilling.invoiceNo ? patientBilling.invoiceNo : patientBilling.prevSysInvoiceNo }}">
                        </div>
                    </div>#}
                </div>
                <div style="width: 24%; float: left; text-align: left; margin-right:7px;">
                    <div class="row">
                        <div class="large-5 columns text-right">
                            {{ form_label(form.serial_no) }}
                        </div>
                        <div class="large-7 columns">
                            {{ form_widget(form.serial_no) }}
                        </div>
                    </div>
                    {% if form.action.vars.value|default('') != 'u' %}
                        <div class="row">
                            <div class="large-5 columns text-right">
                                {{ form_label(form.payer_type) }}
                            </div>
                            <div class="large-7 columns">
                                {{ form_widget(form.payer_type) }}
                            </div>
                        </div>
                    {% else %}
                        <div class="row">
                            <div class="large-5 columns text-right">
                                <label class="required middle required">Payer Type</label>
                            </div>
                            <div class="large-7 columns">
                                {% if patientBilling.payerType is null or patientBilling.payerType == '' %}
                                    {{ form_widget(form.payer_type) }}
                                {% else %}
                                    {{ form_widget(form.payer_type, {attr: {class: 'hide'}}) }}
                                    <input type="text" readonly value="{{ patientBilling.payerType }}" >
                                {% endif %}
                            </div>
                        </div>
                    {% endif %}
                    {% if patientBilling.patient.fullName|default('') == 'Mismatched Invoice' %}
                        <div class="row">
                            <div class="large-5 columns text-right">
                                {{ form_label(form.patient_fullName) }}
                            </div>
                            <div class="large-7 columns">
                                {{ form_widget(form.patient_fullName) }}
                            </div>
                        </div>
                    {% endif %}
                    {#{% if form.action.vars.value|default('') != 'u'  %}#}
                    <div class="row {{ patientBilling.payerType != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::PAYER_TYPE_INSURANCE') ? 'hide' : '' }}"  id="patientBillingForm-patientInsurance-container">
                        <div class="large-5 columns text-right">
                            {{ form_widget(form.patientInsurance) }}
                            {{ form_label(form.patientInsurance_insurance_description) }}
                        </div>
                        <div class="large-7 columns">
                            {{ form_widget(form.patientInsurance_insurance_description) }}
                        </div>
                    </div>
                    {#{% else %}
                        <div class="row {{ form.payer_type.vars.value == '' or form.payer_type.vars.value == constant('RxConnexionBundle\\Entity\\PatientBillingEntity::PAYER_TYPE_SELF_PAY') ? 'hide' : '' }}" id="patientBillingForm-patientInsurance-container">
                            <div class="large-4 columns text-right">
                                {{ form_label(form.patientInsurance_insurance_description) }}
                            </div>
                            <div class="large-8 columns">
                                <input type="text" readonly name="patientBilling[patientInsurance_insurance_description]" value="{{ patientBilling.patientInsurance.insurance.description|default('') }}">
                                {{ form_widget(form.patientInsurance) }}
                            </div>
                        </div>
                    {% endif %}#}
                </div>
                <div style="width: 24%; float: right; text-align: left; margin-right:7px;">
                    {#{% if patientBilling.healthFacility.id|default('') == '' %}#}
                    <div class="row">
                        <div class="large-6 columns text-right">
                            {{ form_label(form.healthFacility_desc) }}
                        </div>
                        <div class="large-6 columns">
                            {{ form_widget(form.healthFacility_desc) }}
                            {{ form_widget(form.healthFacility) }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-6 columns text-right">
                            {{ form_label(form.healthFacilityForAddress_desc) }}
                        </div>
                        <div class="large-6 columns">
                            {{ form_widget(form.healthFacilityForAddress_desc) }}
                            {{ form_widget(form.healthFacilityForAddress) }}
                        </div>
                    </div>
                    {#{% else %}
                    <div class="row">
                        <div class="large-4 columns text-right">
                            {{ form_label(form.healthFacility_desc) }}
                        </div>
                        <div class="large-8 columns">
                            <input type="text" readonly name="patientBilling[healthFacility_desc]" value="{{ patientBilling.healthFacility.description|default('') }}">
                            {{ form_widget(form.healthFacility) }}
                        </div>
                    </div>
                        <div class="row">
                        <div class="large-4 columns text-right">
                            {{ form_label(form.healthFacilityForAddress_desc) }}
                        </div>
                        <div class="large-8 columns">
                            <input type="text" readonly id="patientBilling_healthFacilityForAddress_desc" name="patientBilling[healthFacilityForAddress_desc]" value="{{ patientBilling.healthFacilityForAddress.description|default('') }}">
                            {{ form_widget(form.healthFacilityForAddress) }}
                        </div>
                    </div>
                    {% endif %}#}
                </div>
                <div style="width: 24%; float: right; text-align: left; margin-right:7px;">
                    <div class="row">
                        <div class="large-4 medium-6 columns">
                            {{ form_label(form.endorsed_to) }}
                        </div>
                        <div class="large-8 columns">
                            {{ form_widget(form.endorsed_to) }}
                        </div>
                    </div>

                    <div class="row">
                        <div class="large-4 columns">
                            {{ form_label(form.demand_letter_date) }}
                        </div>
                        <div class="large-8 columns">
                            {{ form_widget(form.demand_letter_date) }}
                        </div>
                    </div>

                    <div class="row">
                        <div class="large-4 columns">
                            {{ form_label(form.insurance_claim_date) }}
                        </div>
                        <div class="large-8 columns">
                            {{ form_widget(form.insurance_claim_date) }}
                        </div>
                    </div>


                    <div id="comment-container" style="display: none;">
                        {{ form_label(form.comment) }}
                        {{ form_widget(form.comment) }}
                    </div>


                    {# TO SHOW FINANCING BILLING DETAILS #}
                    {% if form.action.vars.value == 'u' and patientBilling.payerType == 'Financing' and patientBilling.getPatientBillingFinancingPaymentDetail is not null %}
                        <div id="financing-billing-container">
                            <hr>
                            <p class="form-hint-text">Financing Payment Plan:</p>
                            <table style="font-size: 12px">
                                <tr>
                                    <td style="font-weight: bold">Start Date</td>
                                    <td><input type="text" name="patientBillingFinancingPaymentDetail[start_date]" class="date" value="{{ patientBilling.getPatientBillingFinancingPaymentDetail.getStartDateAsString }}"></td>
                                </tr>
                                <tr>
                                    <td style="font-weight: bold">End Date</td>
                                    <td><input type="text" name="patientBillingFinancingPaymentDetail[end_date]" class="date" value="{{ patientBilling.getPatientBillingFinancingPaymentDetail.getEndDateAsString }}"></td>
                                </tr>
                                <tr>
                                    <td style="font-weight: bold">Payment Day</td>
                                    <td><select name="patientBillingFinancingPaymentDetail[payment_day]">
                                            {% set pd = patientBilling.getPatientBillingFinancingPaymentDetail.getPaymentDay %}
                                            {% for key,val in paymentDays %}
                                                <option value="{{ val }}" {{ pd == val ? 'selected' : '' }}>{{ key }}</option>
                                            {% endfor %}
                                        </select>
                                    </td>
                                    {#<td><input type="text" name="patientBilling[patientBillingFinancingPaymentDetail][payment_day]" value="{{ patientBilling.getPatientBillingFinancingPaymentDetail.getPaymentDay|ordinal }}"></td>#}
                                </tr>
                            </table>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        <hr>
        <div class="large-12 columns">
            <div class="row max-width-initial">
                <div class="large-6 columns">
                    <h5 class="subheader">Breakdown</h5>
                </div>
                <div class="large-6 columns">
                    <div class="large-6 columns">

                    </div>
                    <div class="large-7 columns">
                        {% if form.action.vars.value|default('') != 'u' %}
                        <div style="float: right">
                            <input type="button" class="button secondary" value="Add Breakdown"
                                   id="btn-billing-add-breakdown"
                                   style="background-color: #e6e6e6; color: #0a0a0a; border: 1px solid #cacaca;" />
                        </div>
                       <div style="float: right">
                               <select class="{#input-group-field#}" style="/*height: 2.5375rem;*/" id="dropdown-billing-breakdown-type">
                                   <option value="{{ constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_CHART_PROCEDURE') }}">Encounter Procedure</option>
                                   <option value="{{ constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_ITEM') }}" selected>Item</option>
                                   <option value="{{ constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_OTHER') }}">Other</option>
                               </select>
                               {#<span class="input-group-label">Type</span>#}

                       </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            <table width="102%">
                <thead>
                <tr>
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Return' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND') %}
                    <th style="width: 100px;margin: 0;"></th>
                    {% endif %}
                    <th style="font-weight: bold;">Type</th>
                    <th style="font-weight: bold;width: 50%" colspan="3">Details</th>
                    <th class="term_header" style="font-weight: bold;" >{#Term#}</th>
                    <th class="item_type_header" style="font-weight: bold;" >Item Type</th>
                    <th style="width: 50px; font-weight: bold;" class="text-right">Quantity</th>
                    <th style="width: 10%; font-weight: bold;" class="text-right">Price</th>
                    <th style="font-weight: bold;" class="text-right">Amount</th>
                    <th></th>
                </tr>
                </thead>
                <tbody id="tbody-billing-breakdown">
                {% set colspan_ret = 0 %}
                {% set totalRefunded = 0 %}
                {% set totalAmount = 0 %}
                {% if form.action.vars.value == 'n' %}
                    {% set colspan_ret = 8 %}
                {% endif %}

                {% for pbb_form in form.patientBillingBreakdowns %}
                    {% set totalAmount = totalAmount + pbb_form.vars.value.amount %}
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Return' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND') %}
                        {% if pbb_form.vars.value.status != 'Return' %}
                            {% set colspan_ret = 9 %}
                        {% else %}
                            {% set totalRefunded = totalRefunded + pbb_form.vars.value.amount  %}
                            {% set colspan_ret = 9 %}
                        {% endif %}
                    {% endif %}
                        <tr>
                            {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Return' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND') %}
                                    <td>
                                        {% if pbb_form.vars.value.status != 'Return' %}
                                            <a href="javascript:void(0)" class="button {#ask-continue#} {#href-patient-item-return-action#} href-patient-billing-breakdown-return tiny" data-message="Are you sure you want to return this item?" data-id="{{ pbb_form.vars.value.id }}" data-axn="ret" style="width: 100%;background-color: #272775;margin: 0;">Return</a>
                                            <a href="javascript:void(0)" class="button just-continue href-patient-billing-action tiny hide" data-axn="{{ form.action.vars.value }}" style="width: 100%;margin: 0;">Save</a>
                                        {% else %}
                                            <button href="javascript:void(0)" class="button tiny"  style="width: 100%;background: transparent;color: #000;font-weight: bold" disabled>Returned</button>
                                        {% endif %}
                                    </td>
                            {% endif %}
                            <td>{{ pbb_form.vars.value.type }}</td>
                            {% if constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_ITEM') != pbb_form.vars.value.type and constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_OTHER') != pbb_form.vars.value.type %}
                                <td>
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][patientChart_chartNo]"
                                           value="{{ pbb_form.vars.value.patientChart.idAndChartDateAndChartType|default('') }}"
                                           class="pb_pbb_patientChart_chartNo"
                                           placeholder="Encounter"
                                           readonly
                                    />
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][patientChart]"
                                           value="{{ pbb_form.vars.value.patientChart.id|default('') }}"
                                           class="pb_pbb_patientChart"
                                           readonly
                                    />
                                </td>
                            {% endif %}
                            {% if constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_CHART_PROCEDURE') == pbb_form.vars.value.type %}
                                <td colspan="3">
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][chartProcedure_description]"
                                           value="{{ pbb_form.vars.value.chartProcedure.description }}"
                                           class="pb_pbb_chartProcedure_description"
                                           placeholder="Procedure"
                                           readonly
                                    />
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][chartProcedure]"
                                           value="{{ pbb_form.vars.value.chartProcedure.id }}"
                                           class="pb_pbb_chartProcedure"
                                           readonly
                                    />
                                </td>
                            {% elseif constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_ITEM') == pbb_form.vars.value.type %}
                                <td width="140px;">
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][itemCategory_desc]"
                                           value="{{ pbb_form.vars.value.item.itemSubCategory.itemCategory.description|default('') }}"
                                           class="pb_pbb_itemCategory_desc"
                                           placeholder="Item Subcategory"
                                           style="width: 100%; float: left;"
                                           readonly
                                    />
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][itemCategory]"
                                           value="{{ pbb_form.vars.value.item.itemSubCategory.itemCategory.id|default('') }}"
                                           class="pb_pbb_itemCategory"
                                           style="width: 100%; float: right;"
                                           readonly
                                    />
                                </td>
                                <td data-xwidth="90px;">
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][serialNumber]"
                                           value="{{ pbb_form.vars.value.inventorySerialNo.serialNo|default(pbb_form.vars.value.serialNumber|default('')) }}"
                                           class="pb_pbb_item_serial_number hide"
                                           placeholder="Serial No."
                                           style="width: 100%; float: left;"
                                           readonly
                                    />
                                </td>
                                <td width="250px;">
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][item_description]"
                                           value="{{ pbb_form.vars.value.item.description|default('') }}"
                                           class="pb_pbb_item_description"
                                           placeholder="Item"
                                           style="width: 100%; float: left;"
                                           readonly
                                    />
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][item]"
                                           value="{{ pbb_form.vars.value.item.id|default('') }}"
                                           class="pb_pbb_item"
                                           readonly
                                    />
                                </td>
                                <td>
                                    <select disabled="" name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][term_desc]">
                                        <option value="{{ pbb_form.vars.value.term == '' ? '' : '' }}" {{ pbb_form.vars.value.term == '' ? 'selected' : '' }}></option>
                                        <option value="{{ pbb_form.vars.value.term == 'Rent to Own' ? 'Rent to Own' : '' }}" {{ pbb_form.vars.value.term == 'Rent to Own' ? 'selected' : '' }}>Rent to Own</option>
                                        <option value="{{ pbb_form.vars.value.term == 'Long Term Rental' ? 'Long Term Rental' : '' }}" {{ pbb_form.vars.value.term == 'Long Term Rental' ? 'selected' : '' }}>Long Term Rental</option>
                                    </select>
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][term]"
                                           value="{{ pbb_form.vars.value.term|default }}"
                                           class=""
                                           style="width: 50px; float: right;"
                                           readonly
                                    />
                                </td>
                            {% else %}
                                {#<td>
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][tranDateForOther]"
                                           value="{{ pbb_form.vars.value.tranDateForOther }}"
                                           class="pb_pbb_tranDateForOther"
                                           placeholder="MM-DD-YYYY"
                                    />
                                </td>#}
                                <td colspan="4">
                                    <input type="text"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][description]"
                                           value="{{ pbb_form.vars.value.description }}"
                                           class="pb_pbb_description"
                                           placeholder="Description"
                                           readonly
                                    />
                                </td>
                            {% endif %}
                            {#{% if constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_ITEM') == pbb_form.vars.value.type %}#}
                                <td>
                                    <select disabled name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][item_type_desc]" id="">
                                        <option value="{{ pbb_form.vars.value.itemType == '' ? '' : '' }}" {{ pbb_form.vars.value.itemType == '' ? 'selected' : '' }}></option>
                                        <option value="{{ pbb_form.vars.value.itemType == 'Accessory' ? 'Accessory' : '' }}" {{ pbb_form.vars.value.itemType == 'Accessory' ? 'selected' : '' }}>Accessory</option>
                                        <option value="{{ pbb_form.vars.value.itemType == 'CPAP Package' ? 'CPAP Package' : '' }}" {{ pbb_form.vars.value.itemType == 'CPAP Package' ? 'selected' : '' }}>CPAP Package</option>
                                        <option value="{{ pbb_form.vars.value.itemType == 'Medical Supplies' ? 'Medical Supplies' : '' }}" {{ pbb_form.vars.value.itemType == 'Medical Supplies' ? 'selected' : '' }}>Medical Supplies</option>
                                        <option value="Part of CPAP Package" {{ pbb_form.vars.value.itemType == 'Part of CPAP Package' ? 'selected' : '' }}>Part of CPAP Package</option>
                                    </select>
                                    <input type="hidden"
                                           name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][item_type]"
                                           value="{{ pbb_form.vars.value.itemType|default }}"
                                           class=""
                                           style="width: 50px; float: right;"
                                           readonly
                                    />
                                </td>
                            {#{% endif %}#}
                            <td style="clear: both;">
                                <input type="text"
                                       name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][quantity]"
                                       value="{{ pbb_form.vars.value.quantity }}"
                                       class="pb_pbb_quantity txt-billing-for-computation"
                                       style="width: 50px; float: right;"
                                       readonly
                                />
                            </td>
                            <td style="clear: both;">
                                <input type="text"
                                       name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][price]"
                                       value="{{ pbb_form.vars.value.price }}"
                                       class="pb_pbb_price txt-billing-for-computation"
                                       style="width: 75px; float: right;"
                                       readonly
                                />
                            </td>
                            <td class="text-right pb_pbb_amount_td">{{ pbb_form.amount.vars.value|number_format(2, '.', ',') }}</td>
                            <td>
                                <a href="javascript:void(0)" class="btn-billing-remove-breakdown {{ form.action.vars.value|default('') == 'u' ? 'hide' : '' }}">X</a>
                                <input type="hidden"
                                       name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][amount]"
                                       class="pb_pbb_amount"
                                       value="{{ pbb_form.amount.vars.value }}"
                                       readonly
                                />
                                <input type="hidden"
                                       name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][type]"
                                       class="pb_pbb_type"
                                       value="{{ pbb_form.type.vars.value }}"
                                       readonly
                                />
                                <input type="hidden"
                                       name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][id]"
                                       class="pb_pbb_id"
                                       value="{{ pbb_form.id.vars.value }}"
                                       readonly
                                />
                            </td>
                        </tr>
                {% endfor %}
                </tbody>
                <tfoot>
                    {% if form.action.vars.value == 'u' %}
                        <tr>
                            <td colspan="{{ colspan_ret }}" class="text-right">Total Amount:</td>
                            <td class="text-right" id="td-billing-total-amount">{{ totalAmount|number_format(2, '.', ',') }}</td>
                            <td></td>
                        </tr>
                        {% if totalRefunded != 0 %}
                            <tr>
                                <td colspan="{{ colspan_ret }}" class="text-right">Returned:</td>
                                <td class="text-right" id="td-billing-total-refunded">{{ '-'~totalRefunded|number_format(2, '.', ',') }}</td>
                                <td></td>
                                <td></td>
                            </tr>
                        {% endif %}
                    {% endif %}
                    <tr>
                        <td colspan="{{ colspan_ret }}" class="text-right">Total Amount Due:</td>
                        <td class="text-right" id="td-billing-amount-due">{{ form.amount_due.vars.value|number_format(2, '.', ',') }}</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        {% if patientBilling.patientBillingRefundsNotDeleted|length > 0 %}
            <div class="large-12 columns">
                <h5 class="subheader">Refund</h5>
                <table width="100%">
                    <thead>
                    <tr>
                        <th colspan="6" style="font-weight: bold;">Refund Date</th>
                        <th style="font-weight: bold;">Amount</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% set totalAmtRefund = 0 %}
                    {% for patientBillingRefund in patientBilling.patientBillingRefunds %}
                        <tr>
                            <td colspan="6">{{ patientBillingRefund.refundDate|date('m/d/Y') }}</td>
                            <td>{{ patientBillingRefund.amount|number_format(2, '.', ',') }}</td>
                        </tr>
                        {% set totalAmtRefund = totalAmtRefund + patientBillingRefund.amount %}
                    {% endfor %}
                    <tr>
                        <td colspan="6" class="text-right" style="padding-right: 54px;">Total Refunded Amount:</td>
                        <td id="td-billing-amount-due">{{ totalAmtRefund|number_format(2, '.', ',') }}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        {% endif %}
        {% set patientBillingInventories_key = 0 %}
        {% if form.action.vars.value == 'u' %}
        <div class="large-6 columns">
            <h5 class="subheader">Inventory <a href="javascript:void(0)" class="add_inventory_tr"><i class="fa fa-plus"></i></a></h5>
            <table width="100%">
                <thead>
                <tr>
                    <th style="font-weight: bold;">Item</th>
                    <th style="font-weight: bold; width: 200px">Serial No <br> <small>(Empty field will not get saved)</small></th>
                    <th style="font-weight: bold;width: 100px">Quantity</th>
                    <th></th>
                </tr>
                </thead>
                <tbody id="tbody-billing-inventory">
                {% for key,pbb_inv in form.vars.value.patientBillingInventories %}
                    {% set patientBillingInventories_key = key %}
                    <tr class="patientBillingInventories_tr" data-key="{{ key }}">
                        <td valign="top" style="display: flex;position: relative;">
                            <input type="hidden" name="patient_billing_inventories[{{ key }}][id]" value="{{ pbb_inv.id }}"/>
                            <input type="text"
                                   name="patient_billing_inventories[{{ key }}][item_description]"
                                   value="{{ pbb_inv.item.description }}"
                                   class="input-small inventory_item_description disabled"
                                   data-key="{{ key }}"
                                   readonly
                            />
                            <input type="hidden"
                                   name="patient_billing_inventories[{{ key }}][item]"
                                   value="{{ pbb_inv.item.id }}"
                                   class="inventory_item"
                                   data-key="{{ key }}"
                            />

                            <button
                                    type="button"
                                    class="action-button-style no-margin add_package_items_btn"
                                    style="min-width: unset;{{ pbb_inv.item.isPackage ? '' : 'display:none;' }}"
                                    data-toggle="items-dropdown-{{ key }}"
                                    data-items="{{ pbb_inv.item.packageItemsAsArray(patientBilling.healthFacility.id)|json_encode }}"
                                    data-package_qty_name="patient_billing_inventories[{{ key }}][quantity]"
                                ><i class="fa fa-plus-circle"></i>
                            </button>

                            <div class="dropdown-pane hide" id="items-dropdown-{{ key }}" data-dropdown data-auto-focus="true">
                                <p><em>Select Package Item/s you want to add:</em></p>
                                <ul>
                                    {% for ii in pbb_inv.item.items %}
                                        <li>
                                            {{ ii.description }}
                                            {% if patientBilling.itemIdIsInInventory(ii.id) == false %}
                                                <a href="javascript:void(0)"
                                                   class="href-add-inventory"
                                                   data-item_id="{{ ii.id }}"
                                                   data-item_description="{{ ii.description }}"
                                                   data-package_item_quantity="{{ ii.packageItemQuantity }}"
                                                   data-toggle="items-dropdown-{{ key }}"
                                                ><i class="fa fa-plus-circle"></i>
                                                </a>
                                            {% else %}
                                                <i class="fa fa-check-circle"></i>
                                            {% endif %}
                                        </li>
                                    {% endfor %}
                                </ul>
                            </div>
                        </td>
                        <td valign="top" class="patientBillingInventories_serialNo_td" data-key="{{ key }}">
                            {% if pbb_inv.item.isItemised %}
                                {% for key_inv_sn,inv_sn in pbb_inv.inventorySerialNos %}
                                    <div style="display:flex; ">
                                        <select name="patient_billing_inventories[{{ key }}][inventory_serial_no][]"
                                                class="input-small select2 inventory_serial_no_select"
                                                style="{{ pbb_inv.item.isItemised ? '' : 'display:none;' }}">
                                            <option value=""></option>
                                            <option value="{{ inv_sn.id }}" selected>{{ inv_sn.serialNo }}</option>
                                            {% for sn in pbb_inv.inventory.availableInventorySerialNos %}
                                                <option value="{{ sn.id }}">{{ sn.serialNo }}</option>
                                            {% endfor %}
                                        </select>
                                        <button type="button" class="action-button-style remove_serial_input_btn" data-key="{{ key }}" ><i class="fa fa-close"></i></button>
                                    </div>
                                {% else %}
                                    {% if pbb_inv.quantity > 0 %}
                                        {% for key_qty in 1..pbb_inv.quantity %}
                                            <div style="display: flex;">
                                                <select name="patient_billing_inventories[{{ key }}][inventory_serial_no][]"
                                                        class="input-small select2 inventory_serial_no_select"
                                                        style="{{ pbb_inv.item.isItemised ? '' : 'display:none;' }}">
                                                    <option value=""></option>
                                                    {% for sn in pbb_inv.inventory.availableInventorySerialNos %}
                                                        <option value="{{ sn.id }}">{{ sn.serialNo }}</option>
                                                    {% endfor %}
                                                </select>
                                                <button type="button" class="action-button-style remove_serial_input_btn" data-key="{{ key }}" ><i class="fa fa-close"></i></button>
                                            </div>
                                        {% endfor %}
                                    {% endif %}
                                {% endfor %}
                            {% else %}
                                {#{% for sn in pbb_inv.serialNoToArray %}
                                    <input type="text"
                                           name="patient_billing_inventories[{{ key }}][serial_no][]"
                                           value="{{ sn }}"
                                           class="input-small serial_no_input"
                                           style="{{ pbb_inv.item.isItemised ? 'display:none;' : '' }}"
                                    />
                                {% else %}
                                    {% if pbb_inv.quantity > 0 %}
                                        {% for key_qty in 1..pbb_inv.quantity %}
                                            <input type="text"
                                               name="patient_billing_inventories[{{ key }}][serial_no][]"
                                               value=""
                                               class="input-small serial_no_input"
                                               style="{{ pbb_inv.item.isItemised ? 'display:none;' : '' }}"
                                            />
                                        {% endfor %}
                                    {% endif %}
                                {% endfor %}#}
                            {% endif %}
                        </td>
                        <td valign="top">
                            <div style="display: flex;">
                                <input type="text"
                                       name="patient_billing_inventories[{{ key }}][quantity]"
                                       value="{{ pbb_inv.quantity }}"
                                       class="input-small quantity"
                                        {{ pbb_inv.item.isItemised ? 'readonly' : '' }}
                                />
                                <button data-serial_nos="{{ pbb_inv.inventory.availableInventorySerialNosForSelectInputAsArray|json_encode }}" type="button" class="action-button-style add_serial_input_btn {{ pbb_inv.item.isItemised ? '' : 'hide' }}" data-is_itemised="{{ pbb_inv.item.isItemised ? 1 : 0 }}" data-key="{{ key }}"><i class="fa fa-plus"></i></button>
                            </div>
                        </td>
                        <td valign="top">
                            <a href="javascript:void(0)" class="remove_patient_billing_inventories_btn" data-key="{{ key }}" style="color:red;"><i class="fa fa-trash"></i></a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
        {% endif %}
        {% if form.action.vars.value == 'u' %}
        <div class="large-6 columns">
            <h5 class="subheader">Amount Covered</h5>
            <table width="100%">
                <thead>
                <tr>
                    <th style="font-weight: bold;">Item</th>
                    <th class="text-right" style="font-weight: bold;">Qty</th>
                    <th class="text-right" style="font-weight: bold;">Price</th>
                    <th class="text-right" style="font-weight: bold;">Amount</th>
                    <th class="text-right" style="font-weight: bold;">Frequency</th>
                    <th class="text-right" style="font-weight: bold;">Benefit Period</th>
                    <th class="text-right" style="font-weight: bold;">Covered Price</th>
                    <th class="text-right" style="font-weight: bold;">Covered Amount</th>
                </tr>
                </thead>
                <tbody id="tbody-billing-amount-covered">
                {% for pbb2 in form.patientBillingBreakdowns %}
                    {% set pbb2_item = '' %}
                    {% if pbb2.vars.value.type == constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_CHART_PROCEDURE') %}
                        {% set pbb2_item = pbb2.vars.value.patientChart.idAndChartDateAndChartType %}
                    {% elseif pbb2.vars.value.type == constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_ITEM') %}
                        {% set pbb2_item = pbb2.vars.value.item.description %}
                    {% elseif pbb2.vars.value.type == constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::TYPE_OTHER') %}
                        {% set pbb2_item = pbb2.vars.value.description %}
                    {% endif %}
                    <tr>
                        <td>{{ pbb2_item }}</td>
                        <td>{{ pbb2.vars.value.quantity|number_format(2, '.', ',') }}</td>
                        <td>{{ pbb2.vars.value.price|number_format(2, '.', ',') }}</td>
                        <td>{{ pbb2.vars.value.amount|number_format(2, '.', ',') }}</td>
                        <td>
                            <input type="text"
                                   name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][frequency]"
                                   value="{{ pbb2.vars.value.frequency|default('') }}"
                                   class="input-small"
                                   placeholder=""
                                   style="float: left;"
                            />
                        </td>
                        <td>
                            <select name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][benefitPeriod]" class="input-small" style="width: 100%">
                                <option value="{{ pbb2.vars.value.benefitPeriod == '' ? '' : '' }}" {{ pbb2.vars.value.benefitPeriod == '' ? 'selected' : '' }}></option>
                                <option value="{{ constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::BENEFIT_PERIOD_CALENDAR_YEAR') }}" {{ pbb2.vars.value.benefitPeriod == 'Calendar Year' ? 'selected' : '' }}>Calendar Year</option>
                                <option value="{{ constant('RxConnexionBundle\\Entity\\PatientBillingBreakdownEntity::BENEFIT_PERIOD_BENEFIT_YEAR') }}" {{ pbb2.vars.value.benefitPeriod == 'Benefit Year' ? 'selected' : '' }}>Benefit Year</option>
                            </select>
                        </td>
                        <td><input data-qty="{{ pbb2.vars.value.quantity|number_format(2, '.', ',') }}" type="text" name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][price_covered]" value="{{ pbb2.vars.value.priceCovered|number_format(2, '.', ',') }}" class="amount input-small price-covered-txt" data-idx="{{ loop.index0 }}"></td>
                        <td><input data-qty="{{ pbb2.vars.value.quantity|number_format(2, '.', ',') }}" type="text" name="patientBilling[patientBillingBreakdowns][{{ loop.index0 }}][amount_covered]" value="{{ pbb2.vars.value.amountCovered|number_format(2, '.', ',') }}" class="amount input-small amount-covered-txt" readonly data-idx="{{ loop.index0 }}"></td>
                    </tr>
                {% endfor %}
                </tbody>
                <tfoot>
                    {#<tr>#}
                        {#<td colspan="2" class="text-right" style="padding-right: 54px;">Total Amount Covered:</td>#}
                        {#<td id="td-billing-total-covered">#}{#{{ patientBilling.amountPaid|number_format(2, '.', ',') }}#}{#</td>#}
                    {#</tr>#}
                </tfoot>
            </table>
        </div>
        {% endif %}
        <div class="columns large-6">
            {#<div class="row max-width-initial">#}
                {#<div class="large-12 columns">#}
                    {#<div class="large-6 columns">#}
            {% if form.action.vars.value|default('') == 'n' == 'n' %}
                {% if userData.type == 'Super Admin' or 'Admin Patient Billing Upload' in userData.accesses %}
                    <div id="insurance_package" class="hide">
                        <h5 class="subheader">Insurance Package</h5>
                        <input type="hidden" id="file_type_id" name="form[file_type_id]" style="float: left">
                        <label for="file_type">File Type</label>
                        <div><input type="text" id="file_type" name="" style="float: left; width: 50%;" required></div>
                        <input type="file" name="form[file]" style="float: left; width: 100%;" id="insurance_package_file" required>
                    </div>
                {% endif %}
            {% endif %}
                    {#</div>#}
                    {#<div class="large-6 columns">#}
                    {#</div>#}
                {#</div>#}
            {#</div>#}
        </div>
        <div class="columns large-6">
            {#<div class="row max-width-initial">#}
                {#<div class="large-12 columns">#}
                    {#<div class="large-6 columns">#}
                        <h5 class="subheader">Notes</h5>
                        {#{{ form_label(form.note) }}#}
                        {{ form_widget(form.note) }}
                    {#</div>#}
                    {#<div class="large-6 columns">#}
                    {#</div>#}
                {#</div>#}
            {#</div>#}
        </div>
        {% if patientBilling.patientPayments|length > 0 %}
            <div class="large-12 columns">
                <h5 class="subheader">Payments</h5>
                <table width="100%">
                    <thead>
                    <tr>
                        <th style="font-weight: bold;">Payment Date</th>
                        <th style="font-weight: bold;">Payment Type</th>
                        <th style="font-weight: bold;">Status</th>
                        <th style="font-weight: bold;">Amount</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for patientPayment in patientBilling.patientPayments %}
                        <tr>
                            <td>{{ patientPayment.payDateAsString }}</td>
                            <td>{{ patientPayment.payType }}</td>
                            <td>{{ patientPayment.paymentStatus }}</td>
                            <td>{{ patientPayment.amount|number_format(2, '.', ',') }}</td>
                        </tr>
                    {% endfor %}
                    <tr>
                        <td colspan="3" class="text-right" style="padding-right: 54px;">Total Amount Paid:</td>
                        <td id="td-billing-amount-due">{{ patientBilling.amountPaid|number_format(2, '.', ',') }}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        {% endif %}
        {% if form.action.vars.value|default('') == 'u' == 'u' %}
            <div class="large-12 columns">
                <div class="row max-width-initial">
                    <div class="large-6 columns">
                        <h5 class="subheader">History</h5>
                        <table width="100%">
                            <thead>
                            <tr>
                                <th style="font-weight: bold;">Notes</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>{{ patientBilling.note }} [ {{ patientBilling.updatedBy|default('') }} ]</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="columns large-6">
                        <h5 class="subheader">&nbsp;</h5>
                        <table width="100%">
                            <thead>
                            <tr>
                                <th style="font-weight: bold;">Updated</th>
                                <th style="font-weight: bold;">Created</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>{{ patientBilling.updatedAt|date('m/d/Y') }} [ {{ patientBilling.updatedBy|default('') }} ]</td>
                                <td>{{ patientBilling.createdAt|date('m/d/Y') }} [ {{ patientBilling.createdBy|default('') }} ]</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="large-12 columns">
                <div class="row max-width-initial">
                    {% if form.action.vars.value|default('') == 'u' == 'u' %}
                        <div class="large-6 columns">
                            {% if userData.type == 'Super Admin' or 'Admin Patient Billing Upload' in userData.accesses %}
                                <div id="insurance_package">
                                    <h5 class="subheader">Insurance Package</h5>
                                    <input type="hidden" id="file_type_id" name="form[file_type_id]" style="float: left">
                                    <label for="file_type">File Type</label>
                                    <div><input type="text" id="file_type" name="" style="float: left; width: 50%;"></div>
                                    <input type="file" name="form[file]" style="float: left; width: 100%;">
                                </div>
                            {% endif %}
                        </div>
                        <div class="large-6 columns">
                            <div id="insurance_package">
                                <h5 class="subheader">Insurance Package File</h5>
                                <table width="100%">
                                    <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>File Type</th>
                                        <th>Description</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <tr>
                                        {% if patientBilling.patientFile is not null %}
                                            <td>{{ patientBilling.patientFile.createdAt|date('m/d/Y')|default('') }}</td>
                                            <td>{{ patientBilling.patientFile.fileType.description|default('') }}</td>
                                            <td><a href="{{ path('patient_billing_download', {patientFile_id : patientBilling.patientFile.id|base64Encode}) }}">{{ patientBilling.patientFile.description|default('') }}</a></td>
                                        {% else %}
                                            <td>No File Found.</td>
                                        {% endif %}
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    {% endif %}

                </div>
            </div>
        {% endif %}
    </div>
    <hr>
    <div class="row-max-width-initial">
        <div class="small-12 columns no-padding-right">
            {% if patientBilling.billingStatus not in [constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND'), constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_RETURNED'), constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_VOID')] %}
                <div class="button-container text-right">
                    {#{% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Update' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND') %}
                        <button type="button" class="button href-patient-billing-update" style="background-color: grey;">Update</button>
                    {% endif %}#}
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Refund' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_REFUND') %}
                        <a href="javascript:void(0)" class="button ask-continue href-patient-billing-action" data-message="Are you sure you want to refund this record?" data-axn="ref" style="background-color: #098000">Refund</a>
                    {% endif %}
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Return' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_RETURNED') %}
                        <a href="javascript:void(0)" class="button ask-continue href-patient-billing-action" data-message="Are you sure you want to return this record?" data-axn="ret" style="background-color: #272775">Return</a>
                    {% endif %}
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Void' in userData.accesses) and patientBilling.billingStatus != constant('RxConnexionBundle\\Entity\\PatientBillingEntity::BILLING_STATUS_VOID') %}
                        <a href="javascript:void(0)" class="button ask-continue href-patient-billing-action" data-message="Are you sure you want to void this record?" data-axn="v" style="background-color: red">Void</a>
                    {% endif %}
                    {% if form.action.vars.value == 'n' or (form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Update' in userData.accesses)) or patientBilling.patient.fullName == 'Mismatched Invoice' or  patientBilling.healthFacility.description|default('') == '' or  patientBilling.healthFacilityForAddress.description|default('') == '' %}
                        <a href="javascript:void(0)" class="button just-continue href-patient-billing-action" data-axn="{{ form.action.vars.value }}"
                           data-message="Are you sure you want to save this information?"
                           style="margin-left: 10px; margin-right: 0;"
                        >Save</a>
                        <a href="javascript:void(0)" class="button just-continue href-patient-billing-action" data-close_modal="true" data-axn="{{ form.action.vars.value }}"
                           data-message="Are you sure you want to save this information?"
                           style="margin-left: 10px; margin-right: 0;"
                        >Save & Close</a>
                    {% endif %}
                    {% if form.action.vars.value == 'u' and (userData.type == 'Super Admin' or 'Admin Patient Billing Delete' in userData.accesses) %}
                        <a href="javascript:void(0)" class="ask-continue button alert href-patient-billing-action" data-axn="d"
                           data-message="Are you sure you want to delete this record?"
                           style="margin-left: 10px; margin-right: 0;"
                        >Delete</a>
                    {% endif %}
                    <a href="javascript:void(0)" class="button secondary" data-close style="margin-left: 10px; margin-right: 0;">Close</a>
                </div>
            {% endif %}
        </div>
    </div>
    {{ form_widget(form.amount_due) }}
    {{ form_widget(form.action) }}
    {{ form_widget(form.id) }}
    {{ form_widget(form.patient) }}
    {{ form_widget(form._token) }}
</form>
<script>
    const patient_billing_form = {
        patientBillingInventories_key: 0,
        url: {
            insurance_package_url: null,
            item_autocomplete: null,
            inv_serial_no_autocomplete: null,
        },
        init: () => {
            patient_billing_form.bindAutocomplete();
            patient_billing_form.bindInputs();
            global.maskInput();
            jQ('.select2').select2();
            jQ('#tbody-billing-inventory').delegate('.select2', 'select2:select', function (e) {
                jQ(this).parent().parent().next().find('.add_serial_input_btn').click();
            });
            jQ('#tbody-billing-inventory').delegate('.serial_no_input', 'keyup', function (e) {
                if (e.key === 'Enter' || e.keyCode === 13) {
                    jQ(this).parent().parent().next().find('.add_serial_input_btn').click();
                }
            });
            jQ('#tbody-billing-inventory').delegate('.serial_no_input', 'blur', function (e) {
                if(jQ(this).val() === '') {
                }
            });
            jQ('#tbody-billing-inventory').delegate('.remove_serial_input_btn', 'click', function () {
                let key = jQ(this).data('key'),
                    serialNo_td = jQ(`.patientBillingInventories_serialNo_td[data-key="${key}"]`);

                jQ(this).parent().remove();
                jQ(`input[name="patient_billing_inventories[${key}][quantity]"]`).val(serialNo_td.find('.inventory_serial_no_select').length);
            });
        },
        bindAutocomplete: () => {
            global.autocomplete.bind(patient_billing_form.url.insurance_package_url, '#file_type', '#file_type_id');
            jQ('.inventory_item_description').each(function (i, el) {
                const key = jQ(el).data('key'),
                    desc = jQ(el).attr('name'),
                    id = jQ(el).siblings('.inventory_item').attr('name');

                global.autocomplete.bind(patient_billing_form.url.item_autocomplete, `[name="${desc}"]`, `[name="${id}"]`, {
                    onSelect: function (data) {
                        let serialSelect = jQ(`[name="patient_billing_inventories[${key}][inventory_serial_no][]"]`),
                            serialInput = jQ(`[name="patient_billing_inventories[${key}][serial_no][]"]`),
                            qtyInput = jQ(`[name="patient_billing_inventories[${key}][quantity]"]`),
                            addSerialInputBtn = jQ(`.add_serial_input_btn[data-key="${key}"]`);

                        if(data['is_itemised'] === "1") {
                            let serialNos = data['serialNos'] !== undefined && data['serialNos'] !== null && data['serialNos'] !== '' ? data['serialNos'].split(',') : [];

                            qtyInput.prop('readonly', true);
                            serialInput.val('');
                            serialSelect.show();
                            serialInput.hide();

                            serialSelect.html(`<option value=""></option>`);

                            for(let i=0; i< serialNos.length; i++) {
                                let arr = serialNos[i].split('~');
                                serialSelect.append(`<option value="${arr[0]}">${arr[1]}</option>`)
                            }

                            jQ('.select2').select2();
                            addSerialInputBtn.removeClass('hide').attr({
                                'data-is_itemised':  1,
                                'data-serial_nos': JSON.stringify(serialNos),
                            });

                        } else {

                            qtyInput.prop('readonly', false);
                            serialSelect.val('');
                            serialSelect.hide();
                            serialInput.show();
                            addSerialInputBtn.addClass('hide').attr({
                                'data-is_itemised': 0
                            });

                        }

                        setTimeout(function(){
                            global.formSubmittedReverse();
                        }, 500)

                    }
                });
                jQ(`[name="${desc}"]`).devbridgeAutocomplete('setOptions', {params: {healthFacility_id: '{{ patientBilling ? patientBilling.healthFacility.id|default(0) : 0 }}' }});

            });

            jQ('.inv_sn_autocomplete_container').each(function (i, el) {
                const desc = jQ(el).find('input[type="text"]').attr('name'),
                    initial_value = jQ(el).find('input[type="text"]').data('value'),
                    id = jQ(el).find('input[type="hidden"]').attr('name'),
                    item_id = jQ(this).parent().prev().find('.inventory_item').val();

                global.autocomplete.bind(patient_billing_form.url.inv_serial_no_autocomplete, `[name="${desc}"]`, `[name="${id}"]`);
                 jQ(`[name="${desc}"]`).devbridgeAutocomplete('setOptions', {params: {include: initial_value, item_id: item_id, status: '{{ constant('RxConnexionBundle\\Entity\\InventorySerialNoEntity::STATUS_1')}}'}});
            });
        },
        addInventoryTR: (item_id = '', item_description = '', quantity = '', is_itemised = false, serial_nos = []) => {
            patient_billing_form.patientBillingInventories_key ++;

            /*NOTE: SORRY, CHANGE IT TO jQ ELEMENT CREATION IF MAY TIME. -waeil*/
            let tr = `
                <tr class="patientBillingInventories_tr" data-key="${patient_billing_form.patientBillingInventories_key}">
                        <td valign="top" style="display: flex;position: relative;">
                            <input type="hidden" name="patient_billing_inventories[${patient_billing_form.patientBillingInventories_key}][id]" value="">
                            <input type="text" name="patient_billing_inventories[${patient_billing_form.patientBillingInventories_key}][item_description]" value="${item_description}" class="input-small inventory_item_description" data-key="${patient_billing_form.patientBillingInventories_key}" autocomplete="off">
                            <input type="hidden" name="patient_billing_inventories[${patient_billing_form.patientBillingInventories_key}][item]" value="${item_id}" class="inventory_item" data-key="${patient_billing_form.patientBillingInventories_key}">

                            <button type="button" class="action-button-style no-margin add_package_items_btn" style="min-width: unset;display:none;"><i class="fa fa-plus"></i></button>
                        </td>
                        <td valign="top" class="patientBillingInventories_serialNo_td" data-key="${patient_billing_form.patientBillingInventories_key}">
                           </td>
                        <td valign="top">
                            <div style="display: flex;">
                                <input type="text" name="patient_billing_inventories[${patient_billing_form.patientBillingInventories_key}][quantity]" value="${quantity}" class="input-small quantity" >
                                <button type="button" class="action-button-style add_serial_input_btn ${is_itemised ? '' : 'hide'}" data-serial_nos='${JSON.stringify(serial_nos)}' data-is_itemised="${is_itemised ? 1 : 0}" data-key="${patient_billing_form.patientBillingInventories_key}" ><i class="fa fa-plus"></i></button>
                            </div>
                        </td>
                        <td valign="top">
                            <a href="javascript:void(0)" class="remove_patient_billing_inventories_btn" data-key="${patient_billing_form.patientBillingInventories_key}" style="color:red;"><i class="fa fa-trash"></i></a>
                        </td>
                    </tr>
                `;

            jQ('#tbody-billing-inventory').append(tr);
            patient_billing_form.bindAutocomplete();
            patient_billing_form.bindInputs();
            global.maskInput();
            jQ(`[name="patient_billing_inventories[${patient_billing_form.patientBillingInventories_key}][item_description]"]`).focus();
        },
        bindInputs: () => {
            jQ(".pb_pbb_quantity").maskMoney({precision: 0});
            jQ('.href-patient-billing-update').unbind('click').bind('click', function() {
                if(jQ(this).text() === "Update"){
                    jQ(this).text('Cancel Update');
                    jQ('.pb_pbb_quantity').removeAttr('readonly');
                    jQ('.pb_pbb_price').removeAttr('readonly');
                    jQ("#modal-full").animate({
                        scrollTop: 200
                    }, 500);
                } else {
                    jQ(this).text('Update');
                    jQ('.pb_pbb_quantity').attr('readonly', true);
                    jQ('.pb_pbb_price').attr('readonly', true);
                }
            });
            jQ('.href-patient-billing-breakdown-return').unbind('click').bind('click', function() {
                if(jQ(this).text() === "Return"){
                    jQ(this).text('Cancel').css('background-color','#5f5f5f');
                    // jQ(this).next().removeClass('hide').bind('click', function(e){
                    //     jQ(this).attr('disabled', true).addClass('disabled');
                    // });
                    jQ('.pb_pbb_quantity').removeAttr('readonly');
                    jQ('.pb_pbb_quantity')[0].focus();
                } else {
                    jQ(this).text('Return').css('background-color','#272775');
                    jQ('.pb_pbb_quantity').attr('readonly', true);
                    // jQ(this).next().addClass('hide').removeClass('disabled').attr('disabled', false);
                }
            });
            jQ('.remove_patient_billing_inventories_btn').unbind('click').bind('click', function () {
                const key = jQ(this).data('key');
                jQ(`.patientBillingInventories_tr[data-key="${key}"]`).remove();
            });
            jQ('.add_inventory_tr').unbind('click').bind('click', function(){
                patient_billing_form.addInventoryTR();
            });
            jQ('.add_package_items_btn').unbind('click').bind('click', function () {
               // let dropdown = jQ(this).data('toggle');
                // jQ(`#${dropdown}`).foundation('toggle');
                // jQ(`#${dropdown}`).toggleClass('visible');
                let items = jQ(this).data('items'),
                    package_qty = jQ(`[name="${jQ(this).data('package_qty_name')}"]`).val();
                if(typeof items === 'String') {
                    items = JSON.parse(items);
                }

                for (let i = 0; i < items.length; i++) {
                    const item = items[i];
                    let item_id = item['item_id'],
                        item_description = item['item_description'],
                        is_itemised = item['is_itemised'],
                        serial_nos = item['serial_nos'],
                        package_item_quantity = parseFloat(item['package_item_quantity']) * parseFloat(package_qty);
                    patient_billing_form.addInventoryTR(item_id, item_description, package_item_quantity, is_itemised, serial_nos);
                }

                jQ(this).hide();

            });
            jQ('.href-add-inventory').unbind('click').bind('click', function () {
               let item_id = jQ(this).data('item_id'),
                   item_description = jQ(this).data('item_description'),
                   package_item_quantity = jQ(this).data('package_item_quantity'),
                   dropdown = jQ(this).data('toggle');
                patient_billing_form.addInventoryTR(item_id, item_description, package_item_quantity);
                // jQ(`#${dropdown}`).foundation('toggle');
                jQ(`#${dropdown}`).toggleClass('visible');
            });
            jQ('.add_serial_input_btn').unbind('click').bind('click', function () {

                let is_itemised = jQ(this).data('is_itemised'),
                    serialNo_td = jQ(this).parent().parent().siblings('.patientBillingInventories_serialNo_td'),
                    key = serialNo_td.data('key'),
                    div = jQ('<div>').css('display', 'flex');

                if(is_itemised == 1) {
                    let serial_nos = jQ(this).data('serial_nos'),
                        idx = serialNo_td.find('.inventory_serial_no_select').length + 1,
                        select = jQ('<select>').attr({
                            name: `patient_billing_inventories[${key}][inventory_serial_no][]`,
                            class: 'input-small select2 inventory_serial_no_select'
                        }),
                        removeBtn = `<button type="button" class="action-button-style remove_serial_input_btn" data-key="${key}" ><i class="fa fa-close"></i></button>`;
                    if(serial_nos === undefined) {
                        serial_nos = [];
                    }
                    select.append(jQ('<option>'));
                    for (let i = 0; i < serial_nos.length; i++) {
                        const serialNo = serial_nos[i].split('~');
                        select.append(jQ('<option>').attr({value: serialNo[0]}).html(serialNo[1]));
                    }
                    div.append(select);
                    div.append(removeBtn);
                    serialNo_td.append(div);
                    jQ('.select2').select2();
                    jQ(this).siblings('input').val(idx);
                    select.select2('open');
                } else {
                    /*let idx = serialNo_td.find('.serial_no_input').length + 1,
                        input = jQ('<input>').attr({
                            type: 'text',
                            name: `patient_billing_inventories[${key}][serial_no][]`,
                            class: 'input-small serial_no_input'
                        });
                    div.append(input);
                    serialNo_td.append(div);
                    jQ(this).siblings('input').val(idx);
                    input.focus();*/
                }

            });
        },
    };

    patient_billing_form.url.insurance_package_url = '{{ path('insurance_package_autocomplete') }}';
    patient_billing_form.url.item_autocomplete = '{{ path('item_autocomplete') }}';
    patient_billing_form.url.inv_serial_no_autocomplete = '{{ path('inventory_serial_no_autocomplete') }}';

    patient_billing_form.patientBillingInventories_key = {{ patientBillingInventories_key }};
    patient_billing_form.init();

</script>