{% set userData = app.session.get('userData') %}
<style>
    .add_serial_input_btn, .remove_serial_input_btn {
        min-width: unset;
        height: unset;
        margin-bottom: 0.5rem!important;
    }
    div.dataTables_wrapper tbody input[type=text]{
        margin-bottom: 0.5rem!important;
    }
</style>
<form id="form-purchaseOrderBreakdownItemDelivery" method="POST">
    <input type="hidden" name="purchaseOrderBreakdown_id" value="{{ purchaseOrderBreakdown_id }}" />
    <h4>{{ page_title }}</h4>
    <div class="content-detail-container">
        <div class="row max-width-initial">
            <div class="large-4 columns">
                <div class="page-detail-header">P.O. Details</div>
                <div class="page-detail">P.O. No.: <span>{{ purchaseOrderBreakdown.pono }}</span></div>
                <div class="page-detail">Supplier: <span>{{ purchaseOrderBreakdown.purchaseOrder.supplier.description|default('') }}</span></div>
            </div>
            <div class="large-4 columns end">
                <div class="page-detail-header">Purchase Request Details</div>
                <div class="page-detail">Control No.: <span>{{ purchaseOrderBreakdown.purchaseOrder.materialRequisition.materialrequisitionno }}</span></div>
            </div>
        </div>
    </div>
    <div id="flash-messages-content-modal"></div>
    <p class="form-hint-text">Enter delivery details below</p>
    <div class="row max-width-initial">
        <div class="large-6 columns">
            <div class="row max-width-initial">
                <div class="large-4 columns">
                    <label class="middle text-right required">Received Date</label>
                </div>
                <div class="large-8 columns">
                    <input type="text" name="purchaseOrderBreakdownItemDelivery[receivedDate]" class="date" value="{{ purchaseOrderBreakdownItemDeliveries[0].receivedDate|date('m/d/Y') }}" placeholder="MM/DD/YYYY" />
                </div>
            </div>
        </div>
    </div>
    <div class="row max-width-initial">
        <div class="large-6 columns">
            <div class="row max-width-initial">
                <div class="large-4 columns">
                    <label class="middle text-right required">DR Date</label>
                </div>
                <div class="large-8 columns">
                    <input type="text" name="purchaseOrderBreakdownItemDelivery[drDate]" class="date" value="{{ purchaseOrderBreakdownItemDeliveries[0].drDate|date('m/d/Y') }}" placeholder="MM/DD/YYYY" />
                </div>
            </div>
            <div class="row max-width-initial">
                <div class="large-4 columns">
                    <label class="middle text-right required">DR No.</label>
                </div>
                <div class="large-8 columns">
                    <input type="text" name="purchaseOrderBreakdownItemDelivery[dr_no]" value="{{ purchaseOrderBreakdownItemDeliveries[0].drNo }}" />
                </div>
            </div>
        </div>
        <div class="large-6 columns">
            <div class="row max-width-initial">
                <div class="large-4 columns">
                    <label class="middle text-right">Invoice Date</label>
                </div>
                <div class="large-8 columns">
                    <input type="text" name="purchaseOrderBreakdownItemDelivery[invoiceDate]" class="date" value="{{ purchaseOrderBreakdownItemDeliveries[0].invoiceDate|date('m/d/Y') }}" placeholder="MM/DD/YYYY" />
                </div>
            </div>
            <div class="row max-width-initial">
                <div class="large-4 columns">
                    <label class="middle text-right">Invoice No.</label>
                </div>
                <div class="large-8 columns">
                    <input type="text" name="purchaseOrderBreakdownItemDelivery[invoice_no]" value="{{ purchaseOrderBreakdownItemDeliveries[0].invoiceNo }}" />
                </div>
            </div>
        </div>
        {#<div class="column hide">
            <div class="row">
                <div class="large-4 large-text-right columns">
                    <label class="middle">Payment Method</label>
                </div>
                <div class="large-8 columns">
                    <select name="purchaseOrderBreakdownItemDelivery[paymentMethod]">
                        <option value="Cash">Cash</option>
                        <option value="Check">Check</option>
                        <option value="Credit">Credit</option>
                    </select>
                </div>
            </div>
        </div>#}
    </div>
    {#<div class="row hide">
        <div class="large-4 large-text-right columns">
            <label class="middle">Bank</label>
        </div>
        <div class="large-8 columns">
            <input type="text" name="purchaseOrderBreakdownItemDelivery[bank_description]" id="purchaseOrderBreakdownItemDelivery_bank_description" />
            <input type="hidden" name="purchaseOrderBreakdownItemDelivery[bank_id]" id="purchaseOrderBreakdownItemDelivery_bank_id" />
        </div>
    </div>#}
    <table class="display responsive" id="purchaseOrderBreakdownItem-datalist-update" width="100%">
        <thead>
        <tr>
            <th>Item</th>
            <th>Qty in P.O.</th>
            <th>Voided Qty</th>
            {#<th>Qty Already Received</th>#}
            {#<th>Location</th>#}
            <th>Qty Delivered</th>
            {#<th>UOM</th>#}
            <th>Serial No/s.</th>
        </tr>
        </thead>
        <tbody>
        {% for key,purchaseOrderBreakdownItemDelivery in purchaseOrderBreakdownItemDeliveries %}
            {% set purchaseOrderBreakdownItem = purchaseOrderBreakdownItemDelivery.purchaseOrderBreakdownItem %}
            <tr>
                <td valign="top">{{ purchaseOrderBreakdownItem.purchaseorderitem.materialrequisitionitem.item.description|default('') }}</td>
                <td valign="top">{{ purchaseOrderBreakdownItem.requiredquantity|number_format(0, '.', ',') }}</td>
                <td valign="top">{{ purchaseOrderBreakdownItem.quantityvoided|number_format(0, '.', ',') }}</td>
                {#<td valign="top">{{ purchaseOrderBreakdownItem.quantityreceived|number_format(0, '.', ',') }}</td>#}
                {#<td>
                    <select name="purchaseOrderBreakdownItems[{{ key }}][location_id]" style="height: auto;">
                        {% for location in purchaseOrderBreakdown.purchaseorder.materialrequisition.branch.locations %}
                        <option value="{{ location.id }}">{{ location.description }}</option>
                        {% endfor %}
                    </select>
                </td>#}
                <td valign="top" style="display: flex">
                    <div>
                        <input type="hidden" name="purchaseOrderBreakdownItemDelivery[deliveries][{{ key }}][purchaseOrderBreakdownItem]" value="{{ purchaseOrderBreakdownItem.id }}" />
                        <input type="hidden" name="purchaseOrderBreakdownItemDelivery[deliveries][{{ key }}][id]" value="{{ purchaseOrderBreakdownItemDelivery.id }}" />
                        <input autocomplete="off" type="text" {{ purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised ? 'readonly' : '' }} class="{{ purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised ? 'itemised_quantity' : '' }} amount" data-key="{{ key }}"  name="purchaseOrderBreakdownItemDelivery[deliveries][{{ key }}][quantity]" value="{{ purchaseOrderBreakdownItemDelivery.quantity }}" />
                        {% if purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised %}
                            <button type="button" class="action-button-style add_serial_input_btn" data-key="{{ key }}" ><i class="fa fa-plus"></i></button>
                        {% endif %}
                    </div>
                </td>
                {#<td>
                    <select name="purchaseOrderBreakdownItems[{{ key }}][unitOfMeasurement]" style="padding: 0px;margin-bottom: 0px;">
                        {% for itemunitmeasurement in purchaseOrderBreakdownItem.purchaseorderitem.materialrequisitionitem.item.itemunitmeasurements %}
                            <option value="{{ itemunitmeasurement.id }}" {% if itemunitmeasurement.id ==  purchaseOrderBreakdownItem.itemunitmeasurement.id %}{{ 'selected' }}{% endif %}>{{ itemunitmeasurement.description }}</option>
                        {% endfor %}
                    </select>
                </td>#}
                <td valign="top" data-key="{{ key }}" class="serialNo_td">
                    {% set sn_index = 0 %}
                    {% for serialNo in purchaseOrderBreakdownItemDelivery.purchaseOrderBreakdownItemDeliverySerialNos %}
                        {% set sn_index = sn_index + 1 %}
                        <div style="display: flex">
                            <input data-key="{{ key }}" type="hidden" name="purchaseOrderBreakdownItemDelivery[deliveries][{{ key }}][serialNo][{{ sn_index }}][id]" value="{{ serialNo.id }}">
                            <input data-key="{{ key }}" type="text"   name="purchaseOrderBreakdownItemDelivery[deliveries][{{ key }}][serialNo][{{ sn_index }}][serialNo]" value="{{ serialNo.serialNo }}" class="purchaseOrderBreakdownItems_serialNo">
                            <button data-key="{{ key }}" type="button" class="action-button-style remove_serial_input_btn" data-index="{{ sn_index }}"><i class="fa fa-minus"></i></button>
                        </div>
                    {% endfor %}
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <br/>
    <div class="row max-width-initial">
        <div class="small-12 columns no-padding-right">
            <div class="button-container text-right">
                <button type="button" class="button just-continue href-purchaseOrderBreakdownItemDelivery-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 Purchase Order Receive Delete' in userData.accesses) %}
                    <button type="button" class="ask-continue button alert href-purchaseOrderBreakdownItemDelivery-action float-right" name="action" value="d"
                            data-message="Are you sure you want to delete this record?"
                    >Delete</button>
                {% endif %}
                <button type="button" class="button secondary float-right" data-close
                >Cancel</button>
            </div>
        </div>
    </div>
    <input type="hidden" class="form-action" name="purchaseOrderBreakdownItemDelivery[action]">
</form>

<script>

    const po_receive_form = {
        init: function () {
            po_receive_form.bindRemoveSerial();
            po_receive_form.bindAddSerial();
        },
        bindAddSerial: function () {
            jQ('.add_serial_input_btn').unbind('click').bind('click', function () {
                let key = jQ(this).data('key');
                po_receive_form.addSerialInputByKey(key);
            });
            jQ('.purchaseOrderBreakdownItems_serialNo').unbind('keyup').bind('keyup', function (e) {
                let key = jQ(this).data('key');
                if (e.key === 'Enter' || e.keyCode === 13) {
                    po_receive_form.addSerialInputByKey(key);
                }
            });
        },
        bindRemoveSerial: function () {
            jQ('.remove_serial_input_btn').unbind('click').bind('click', function () {
                let key = jQ(this).data('key');
                jQ(this).parent().remove();
                po_receive_form.updateQuantityByKey(key);
            });
        },
        updateQuantityByKey: function (key) {
            let qty = jQ(`.purchaseOrderBreakdownItems_serialNo[data-key="${key}"]`).length;
            jQ(`.itemised_quantity[data-key="${key}"]`).val(qty === 0 ? '' : qty);
        },
        addSerialInputByKey: function (key) {
            let serialNo_td = jQ(`.serialNo_td[data-key="${key}"]`),
                indexes = [],
                i = 0;

            serialNo_td.find('.purchaseOrderBreakdownItems_serialNo').each(function (index, el) {
                indexes.push(parseInt(jQ(el).data('index')));
            });

            if(indexes.length > 0) {
                i = Math.max.apply(null, indexes) + 1;
            }

            let div = jQ('<div>').css({'display': 'flex'}),
                input = jQ('<input>').attr({
                    type: 'text',
                    class: 'purchaseOrderBreakdownItems_serialNo',
                    name: `purchaseOrderBreakdownItemDelivery[deliveries][purchaseOrderBreakdownItems][${key}][serialNo][${i}][serialNo]`,
                    'data-key': key,
                    'data-index': i,
                }),
                removeBtn = jQ('<button>').attr({
                    type: 'button',
                    class: 'action-button-style remove_serial_input_btn',
                    'data-key': key,
                    'data-index': i,
                }).html('<i class="fa fa-minus"></i>');

            div.append(input);
            div.append(removeBtn);
            div.appendTo(serialNo_td);

            po_receive_form.updateQuantityByKey(key);
            po_receive_form.bindRemoveSerial();
            po_receive_form.bindAddSerial();

            input.focus();

        },
    };

    po_receive_form.init();



    /*jQ('.itemised_quantity').unbind('input blur').bind('input blur', function (e) {
        let _this = this,
            key = jQ(_this).data('key'),
            qty = jQ(_this).val(),
            serialNo_inputs = [],
            serialNo_td = jQ(_this).parent().parent().find('.serialNo_td');

        jQ(_this).parent().parent().find('.purchaseOrderBreakdownItems_serialNo').each(function (index, el) {
            serialNo_inputs.push(el);
        });

        for(let i = 0; i < qty; i++) {
            if(serialNo_inputs[i] === undefined) {
                serialNo_td.append(`<input type="text" class="purchaseOrderBreakdownItems_serialNo" name="purchaseOrderBreakdownItems[${key}][serialNo][${i}]" value="" />`)
            }
        }

        if(qty > serialNo_inputs || e.type === "blur") {
            jQ(_this).parent().parent().find('.purchaseOrderBreakdownItems_serialNo').each(function (index, el) {
                if ((index + 1) > qty) {
                    jQ(el).remove();
                }
            });
        }

        jQ(_this).parent().parent().find('.serialNo_td > .action-button-style').addClass('hide');

    });*/


    /*jQ('.generate_serial_inputs_btn').unbind('click').bind('click', function () {
        let _this = this,
            key = jQ(_this).data('key'),
            qty = jQ(_this).parent().parent().find('.itemised_quantity').val(),
            serialNo_inputs = [],
            serialNo_td = jQ(_this).parent().parent().find('.serialNo_td');

        jQ(_this).parent().parent().find('.purchaseOrderBreakdownItems_serialNo').each(function (index, el) {
            serialNo_inputs.push(el);
        });

        for(let i = 0; i < qty; i++) {
            if(serialNo_inputs[i] === undefined) {
                serialNo_td.append(`<input autocomplete="off" type="text" class="purchaseOrderBreakdownItems_serialNo" name="purchaseOrderBreakdownItems[${key}][serialNo][${i}]" value="" />`)
            }
        }

        jQ(_this).parent().parent().find('.purchaseOrderBreakdownItems_serialNo').each(function (index, el) {
            if((index+1) > qty) {
                jQ(el).remove();
            }
        });
    });*/
</script>