{% 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="{{ 'now'|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="{{ 'now'|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[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="" 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[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" width="100%">
        <thead>
        <tr>
            <th>Item</th>
            <th>Price</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,purchaseOrderBreakdownItem in purchaseOrderBreakdown.purchaseorderbreakdownitems %}
            <tr>
                <td valign="top">{{ purchaseOrderBreakdownItem.purchaseorderitem.materialrequisitionitem.item.description|default('') }}</td>
                <td valign="top">{{ purchaseOrderBreakdownItem.purchaseorderitem.materialrequisitionitem.price|number_format(2, '.', ',') }}</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">
                    <input type="hidden" name="purchaseOrderBreakdownItems[{{ key }}][id]" value="{{ purchaseOrderBreakdownItem.id }}" />
                    <input autocomplete="off" type="text" {{ purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised ? 'readonly' : '' }} class="{{ purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised ? 'itemised_quantity' : '' }} {{ purchaseOrderBreakdownItem.quantityreceived >= purchaseOrderBreakdownItem.requiredquantity ? 'hide' : '' }}" data-key="{{ key }}"  name="purchaseOrderBreakdownItems[{{ key }}][quantity]" value="" />
                    {% if purchaseOrderBreakdownItem.purchaseOrderItem.materialRequisitionItem.item.isItemised %}
                        <button type="button" class="action-button-style add_serial_input_btn {{ purchaseOrderBreakdownItem.quantityreceived >= purchaseOrderBreakdownItem.requiredquantity ? 'hide' : '' }}" data-key="{{ key }}" ><i class="fa fa-plus"></i></button>
                    {% endif %}
                </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">
                </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-actionAll" id="href-purchaseOrderBreakdownItemDelivery-actionAll" name="action" value=""
                        data-message="Are you sure you want to save this information?"
                >Save</button>
                <button type="button" class="button secondary no-margin-right" data-close
                >Cancel</button>
            </div>
        </div>
    </div>
</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);
                }
            });
            jQ('.purchaseOrderBreakdownItems_serialNo').unbind('blur').bind('blur', function (e) {
                let key = jQ(this).data('key');
                po_receive_form.updateQuantityByKey(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 = 0;
            jQ(`.purchaseOrderBreakdownItems_serialNo[data-key="${key}"]`).each(function (i, el) {
                if (jQ(el).val() !== '') {
                    qty++;
                }
            });
            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: `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>