{% set userData = app.session.get('userData') %}
<style>
    .select2 {
        margin-bottom: .5rem;
    }
    .select2-container{
        width: 100%!important;
    }
    .add_serial_input_btn {
        height: unset;
        margin-bottom: .5rem!important;
    }
    .select2-selection{
         min-height: unset!important;
     }
</style>
<form id="form-convertInventoryItem" method="POST">
    <h5>{{ page_title }}</h5>
    <div id="flash-messages-content-modal"></div>
    <p class="form-hint-text">Enter basic information below</p>
    <div class="row">
        <div class="large-4 large-text-right columns">
            {{ form_label(form.inventory_item_description) }}
        </div>
        <div class="large-8 columns">
            {{ form_widget(form.inventory_item_description) }}
            {{ form_widget(form.inventory) }}
        </div>
    </div>
    <div class="row">
        <div class="large-4 large-text-right columns">
            {{ form_label(form.quantity) }}
        </div>
        <div class="large-8 columns" style="display: flex;">
            {{ form_widget(form.quantity, {attr: {readonly : form.vars.value.inventory.item.isItemised|default(false) }}) }}
            <button data-serial_nos="{{ form.vars.value.inventory.availableInventorySerialNosForSelectInputAsArray|default([])|join(',') }}"
                    type="button"
                    class="action-button-style add_serial_input_btn {{ form.vars.value.inventory.item.isItemised|default(false) ? '' : 'hide' }}"
                    data-is_itemised="{{ form.vars.value.inventory.item.isItemised|default(false) }}"><i class="fa fa-plus"></i>
            </button>
        </div>
    </div>
    <div class="row {{ form.vars.value.inventory.item.isItemised|default(false) ? '' : 'hide' }}" id="inventory_serial_no_container">
        <div class="large-4 large-text-right columns">
            <label class="required middle required" for="serial_nos_select">Serial No/s <br> <small>(Empty field will not get saved)</small></label>
        </div>
        <div class="large-8 columns patientBillingInventories_serialNo_td">
            {% for isn in form.vars.value.convertInventoryItemInventorySerialNos %}
            <div style="display: flex;">
                <select name="inventory_serial_no[]" class="input-small select2 inventory_serial_no_select">
                    <option></option>
                    <option value="{{ isn.inventorySerialNo.id }}" selected>{{ isn.inventorySerialNo.serialNo }}</option>
                    {% for sn in form.vars.value.inventory.availableInventorySerialNos %}
                        <option value="{{ sn.id }}">{{ sn.serialNo }}</option>
                    {% endfor %}
                </select>
            </div>
            {% endfor %}
        </div>
    </div>
    <hr>
    <div class="row max-width-initial">
        <div class="small-12 columns no-padding-right">
            <div class="button-container clearfix">
                <button type="button" class="button just-continue href-convertInventoryItem-action float-right" name="action" value="{{ action }}"
                        data-message="Are you sure you want to save this information?"
                >Save</button>
                {% if action == 'u' and (userData.type == 'Super Admin' or 'Admin Convert Inventory Item Update Delete' in userData.accesses) %}
                    <button type="button" class="ask-continue button alert href-convertInventoryItem-action float-right" name="action" value="d"
                            data-message="Are you sure you want to delete this record?"
                    >Delete</button>
                {% endif %}
            </div>
        </div>
    </div>
    {{ form_widget(form.convertInventory) }}
    {{ form_widget(form.action) }}
    {{ form_widget(form.id) }}
    {{ form_widget(form._token) }}
</form>

<script>
    const item_form = {
        init: function () {
            item_form.initAutocomplete();
            item_form.bindAddSerialInput();
            item_form.bindRemoveSerialInput();
            jQ('.select2').select2();
            global.bindFormSubmitted();
            convertInventoryItem.bindHrefConvertInventoryItemAction();
        },
        initAutocomplete: function () {
            global.autocomplete.bind(convertInventoryItem.settings.inventory_autocomplete_url, '#convertInventoryItem_inventory_item_description', '#convertInventoryItem_inventory', {
                onSelect: function (data) {
                    jQ('#serial_nos_select').html('<option></option>');

                    if(data['is_itemised'] == 1) {
                        jQ('.add_serial_input_btn').attr({
                            'data-is_itemised':  data['is_itemised'],
                            'data-serial_nos': data['serialNos'],
                        });
                        jQ('#inventory_serial_no_container, .add_serial_input_btn').removeClass('hide');
                        jQ('#convertInventoryItem_quantity').val('').attr('readonly', true);
                    } else {
                        jQ('.patientBillingInventories_serialNo_td').html('');
                        jQ('#inventory_serial_no_container, .add_serial_input_btn').addClass('hide');
                        jQ('#convertInventoryItem_quantity').val('').attr('readonly', false);
                    }

                }
            });
            jQ('#convertInventoryItem_inventory_item_description').devbridgeAutocomplete('setOptions', {params: {status: 'Stock On Hand', health_facility_id: convertInventoryItem.settings.health_facility_id}});
        },
        bindRemoveSerialInput: function () {
            jQ('#form-convertInventoryItem').delegate('.remove_serial_input_btn', 'click', function () {
                jQ(this).parent().remove();
            });
        },
        bindAddSerialInput: function () {
            jQ('#form-convertInventoryItem').delegate('.add_serial_input_btn', 'click', function () {

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

                if(is_itemised == 1) {
                    let serial_nos = jQ(this).data('serial_nos'),
                        select = jQ('<select>').attr({
                            name: `inventory_serial_no[]`,
                            class: 'input-small select2 inventory_serial_no_select'
                        }).html('<option></option>'),
                        remove_btn = `<button type="button" class="action-button-style remove_serial_input_btn"><i class="fa fa-trash"></i></button>`;

                    if(serial_nos === undefined) {
                        serial_nos = "";
                    }
                    serial_nos = serial_nos.split(',');
                    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(remove_btn);
                    serialNo_td.append(div);
                    jQ('.select2').select2();
                    jQ('#modal-small').foundation('close');
                    jQ('#modal-small').foundation('open');
                    select.select2('open');
                    select.on('select2:select', function (e) {
                        if(e.params.data.id !== '') {
                            let add_flag = true;
                            jQ('.inventory_serial_no_select').each(function (i, el) {
                                if (jQ(el).val() === '') {
                                    jQ(el).select2('open');
                                    add_flag = false;
                                }
                            });
                            if(add_flag) {
                                jQ('.add_serial_input_btn').click();
                            }
                        }
                        item_form.computeQty();
                    });
                    item_form.computeQty();
                }
            });
        },
        computeQty: function () {
            let qty = 0;
            jQ('.inventory_serial_no_select').each(function (i, el) {
                if (jQ(el).val() !== '') {
                    qty++;
                }
            });
            jQ('#convertInventoryItem_quantity').val(qty);
        }
    };

    item_form.init();





</script>