{% extends "base.html.twig" %}
{% trans_default_domain 'core' %}

{% block actionheader %}

{% endblock %}

{% block searchform_container %}{% endblock %}

{% block body %}

    <article class="invoice-like">

        <header id="invoice-like-title" class="clearfix">
            {% block invoice_actions %}{% endblock %}
            {% block invoice_label %}{% endblock %}
        </header>

        {{ form_start(form, {'attr': {'class': 'form-stacked', 'id':'guiaremision' } }) }}

        <div class="box pad box-warning">

            <div class="box-header with-border">

                <div class="btn-group">

                    <a href="{{ path('guiaremision_index') }}" class="btn btn-app">
                        <i class="glyphicon glyphicon-list-alt"></i>
                        Listado
                    </a>
                    <a href="{{ path('guiaremision_add') }}" class="btn btn-app">
                        <i class="glyphicon glyphicon-file"></i>
                        Nuevo
                    </a>

                </div>

            </div>
            <div class="box-body">
                <div class="row">
                    <div id="invoice-like-customer-data" class="col-md-8">

                        {# <h3>{% trans %}abstract_invoice.form.customer{% endtrans %}</h3> #}

                        <div class="row">
                            <div class="col-md-3 col-xs-6 clearfix">
                                {{ form_row(form.series) }}
                            </div>
                            <div class="col-md-3 col-xs-6 clearfix">
                                {{ form_label(form.number) }}
                                {{ form_widget(form.number, {'value' : "%09d"|format(form.number.vars.value) }) }}
                            </div>
                            <div class="col-md-6 col-xs-12 clearfix">
                                {{ form_row(form.issue_date) }}
                            </div>
                        </div>

                        <div class="row">

                            <div class="col-md-4 clearfix">
                                <div class="form-group">
                                    {{ form_label(form.transportista_identification) }}
                                    <div class="input-group">
                                        {{ form_widget(form.transportista_identification) }}
                                        <span class="input-group-btn">
                                            <button id="buscartransportista" type="button"
                                                    class="btn btn-info btn-flat">
                                                <i class="glyphicon glyphicon-search"></i>
                                            </button>
                                        </span>
                                    </div>
                                    {{ form_errors(form.transportista_identification) }}
                                </div>
                            </div>

                            <div class="col-md-8 clearfix">
                                {% if formtransportista is defined %}
                                    {{ form_label(form.transportista_name) }}
                                    <div class="input-group">
                                        {{ form_widget(form.transportista_name) }}
                                        <span class="input-group-btn">
                                          <button type="button" class="btn btn-success btn-flat" data-toggle="modal"
                                                  data-target="#modal-default-transportista"><i
                                                      class="glyphicon glyphicon-plus"></i></button>
                                        </span>
                                    </div>
                                    {{ form_errors(form.transportista_name) }}
                                {% else %}
                                    {{ form_row(form.transportista_name) }}
                                {% endif %}
                            </div>

                        </div>
                        <div class="row">
                            <div class="col-md-6 clearfix">
                                <div class="form-group">
                                    {{ form_label(form.transportista_email) }}
                                    <div class="input-group">
                                <span class="input-group-addon"><span
                                            class="glyphicon glyphicon-envelope"></span></span>
                                        {{ form_widget(form.transportista_email) }}
                                    </div>
                                    {{ form_errors(form.transportista_email) }}
                                </div>
                            </div>

                            <div class="col-md-6 clearfix">
                                {{ form_label(form.transportista_placa) }}
                                {{ form_widget(form.transportista_placa) }}
                            </div>

                        </div>
                        <div class="row">
                            <div class="col-md-12 clearfix">
                                <div class="form-group">
                                    {{ form_label(form.direccionpPartida) }}
                                    {{ form_widget(form.direccionpPartida) }}
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="form-group">
                                <div class="col-md-6 col-xs-12 clearfix">
                                    {{ form_row(form.fecini_transporte) }}
                                </div>
                                <div class="col-md-6 col-xs-12 clearfix">
                                    {{ form_row(form.fecfin_transporte) }}
                                </div>
                            </div>
                        </div>

                    </div>

                    <div style="display: none; visibility: hidden;">
                        <div id="invoice-like-properties" class="col-md-4">
                            <div class="panel panel-default">
                                <h3 class="panel-heading">{% trans %}abstract_invoice.form.properties{% endtrans %}</h3>

                                <div class="panel-body form-inline">
                                    {% block properties_form %}{% endblock %}
                                </div>
                            </div>
                        </div>
                    </div>


                    {% block additional_form_data %}{% endblock %}
                </div>

                <h3>Destinatarios</h3>
                <div class="row">
                    <div class="col-md-12">
                        <table id="guiaremision-like-items" class="table table-condensed table-striped align-middle"
                               data-type="customers">
                            <thead>
                            <tr>
                                <th></th>
                                <th class="">Nombre</th>
                                <th class="col-md-1 cell-align-center">Identificación</th>
                                <th class="col-md-2 cell-align-center">Productos</th>
                            </tr>
                            </thead>
                            <tbody data-prototype="{{ include('GuiaRemision/Item/itemguiaview.html.twig')|e }}">

                            </tbody>
                        </table>
                    </div>
                </div>

                <button type="button" id="invoice-like-add-destinatario"
                        class="btn-sm btn-primary"><span
                            class="glyphicon glyphicon-plus glyphicon-white"></span>&nbsp;Añadir
                    destinatario
                </button>

                <script type="text/javascript">

                    $('#invoice-like-add-destinatario').on('click', function (event) {
                        event.preventDefault();
                        buscarDestinatarioModal();
                    });

                </script>
                <br><br>
                <div id="invoice-like-notes" class="row">
                    <div class="col-md-12">
                        {{ form_row(form.notes) }}
                    </div>
                </div>

                <div id="invoice-like-notes1" class="row">
                    <div class="col-md-12">
                        {{ form_row(form.note1) }}
                    </div>
                </div>

                {% if entity.statusString != 'anulado' and entity.statusString != 'autorizado' %}
                    <button type="submit" class="btn btn-success" name="savesend" id="btn-save">
                        <i class="fa fa-save"></i>&nbsp;Guardar y Enviar SRI
                    </button>&nbsp;&nbsp;
                    <button type="submit" class="btn btn-info" name="save">
                        <i class="fa fa-save"></i>&nbsp;Guardar
                    </button>
                {% endif %}

                <div class="row" style="display: none">
                    <table id="invoice-like-items-dest" class="table table-condensed table-striped align-middle">
                        <tbody id="tbody-items-dest"
                               data-prototype="{{ include('GuiaRemision/Item/destinatario.html.twig', { 'formdestinatario': form.destinatarios.vars.prototype, 'currency': currency })|e }}">

                        {# {% for item in form.destinatarios %}
                            {{ include('GuiaRemision/Item/edit.html.twig', { 'form': item, 'entity': item.vars.value, 'currency': currency }) }}
                        {% endfor %} #}

                        </tbody>
                    </table>
                </div>

                {{ form_rest(form) }}

            </div>

        </div>

        {{ form_end(form) }}

    </article>

    <div class="modalwait">

    </div>

    {% include "Core/transportista.form.html.twig" %}

    {% include "Core/customerguia.form.html.twig" %}

    {% include "GuiaRemision/modalsearch.html.twig" %}

    {% include "GuiaRemision/modaldestinatario.html.twig" with {'entity': entity, 'formdestinatario': formdestinatario } %}

{% endblock %}

    {% block javascripts %}
        {{ parent() }}

        <script src="{{ asset('js/products.js') }}"></script>

        <script>

            $(document).ready(function () {
                $.fn.enterkeytab = function () {
                    $(this).on('keydown', 'input,text', function (e) {
                        var self = $(this)
                            , form = self.parents('form:eq(0)')
                            , focusable
                            , next
                        ;
                        if (e.keyCode == 13) {

                            if (e.currentTarget.id.indexOf('guiaremision_items') !== -1) {

                                if (e.currentTarget.id.indexOf('discount_percent') !== -1) {
                                    console.log('filas ' + svindex);
                                    let row = document.getElementById(e.currentTarget.id);
                                    if (row) {
                                        let tr = $(row).parents('tr').attr('id')
                                        console.log(tr);
                                    }
                                }
                            }
                            focusable = form.find('input').filter(':not(:disabled)');
                            next = focusable.eq(focusable.index(this) + 1);

                            if (next.length) {
                                //if disable try get next 10 fields
                                if (next.is(":disabled")) {
                                    for (i = 2; i < 10; i++) {
                                        next = focusable.eq(focusable.index(this) + i);
                                        if (!next.is(":disabled"))
                                            break;
                                    }
                                }
                                console.log($(next).attr("id"));
                                next.focus();
                            }
                            return false;
                        }
                    });
                }
                $("#guiaremision").enterkeytab();
            });
        </script>

        <script src="{{ asset('js/guiaremision-common.js') }}"></script>

        <script src="{{ asset("js/simpleDialog.min.js") }}"></script>

        <script>

            document.addEventListener('DOMContentLoaded', function () {

                const form = document.getElementById('guiaremision');
                const btnSave = document.getElementById('btn-save');

                if (!form || !btnSave) return;

                form.addEventListener('submit', function () {

                    // Evita doble submit
                    if (btnSave.disabled) {
                        return false;
                    }

                    // Deshabilita el botón
                    btnSave.disabled = true;

                    // Cambia texto / icono
                    btnSave.innerHTML =
                        '<i class="fa fa-spinner fa-spin"></i>&nbsp;Procesando...';

                    // Opcional: bloquear todos los submits
                    const buttons = form.querySelectorAll('button[type="submit"]');
                    buttons.forEach(b => b.disabled = true);

                    // Mostrar overlay si deseas
                    $('.modalwait').show();
                });
            });

            document.querySelectorAll('button[type="submit"]').forEach(btn => {
                btn.addEventListener('click', function () {
                    document.getElementById('submit-action').value = this.name;
                });
            });


            {% set filas =  1 %}
            {% set filas =  form.destinatarios | length %}
            let svindexdes = {{ filas }};

            $(function () {

                /*$(document).on('input', '#guia_remision_transportista_name', function (e) {
                    e.preventDefault();
                    let self = this;
                    if (self.value.length >= 3) {
                        buscarTransportistaModal(self.value);
                    }
                });*/

                $('#formdestinatariosv').submit(function (e) {
                    e.preventDefault();
                    $('#modal-destinatario').modal('hide');

                    let collectionHolder = $('table#invoice-like-items-dest tbody#tbody-items-dest');
                    let prototype = collectionHolder.attr('data-prototype');
                    let index = svindexdes++;

                    let form = prototype.replace(/__name__/g, index);
                    form = form.replace('class="edit-item-row-dest"', 'id="svdest' + index + '" class="edit-item-row-dest"');
                    form1 = form.replace('id="invoice-like-items-destinatario"', 'id="invoice-like-items-destinatario-' + index + '"');
                    collectionHolder.append(form1);

                    document.getElementById("guia_remision_destinatarios_" + index + "_customer_identification").value = document.getElementById("destinatario_customer_identification").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_customer_name").value = document.getElementById("destinatario_customer_name").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_customer_email").value = document.getElementById("destinatario_customer_email").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_dir_destino").value = document.getElementById("destinatario_dir_destino").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_motivoTraslado").value = document.getElementById("destinatario_motivoTraslado").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_ruta").value = document.getElementById("destinatario_ruta").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_motivoTraslado").value = document.getElementById("destinatario_motivoTraslado").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_codEstabDestino").value = document.getElementById("destinatario_codEstabDestino").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_docAduanero").value = document.getElementById("destinatario_docAduanero").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_invoiceSerie").value = document.getElementById("destinatario_invoiceSerie").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_invoiceNumero").value = document.getElementById("destinatario_invoiceNumero").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_invoiceFecha").value = document.getElementById("destinatario_invoiceFecha").value;
                    document.getElementById("guia_remision_destinatarios_" + index + "_invoiceAutorizacion").value = document.getElementById("destinatario_invoiceAutorizacion").value;

                    const tableRows = document.querySelectorAll('#invoice-like-items tbody tr');

                    let index77 = 5;

                    for (let i = 0; i < tableRows.length; i++) {
                        const row = tableRows[i];
                        //const status = row.querySelector('.status');
                        let index2 = row.id;
                        if (index2 === 'undefined' || index2.length === 0)
                            index2 = 0;
                        else
                            index2 = index2.replace('sv', '');

                        index2 = parseInt(index2);

                        let descripcion = document.getElementById('destinatario_items_' + index2 + '_description').value;
                        let cantidad = document.getElementById('destinatario_items_' + index2 + '_quantity').value;

                        let filaaux = '<tr>' +
                            '<td>' +
                            '<input type="text" id="guia_remision_destinatarios_' + index + '_items_' + index77 + '_description" name="guia_remision[destinatarios][' + index + '][items][' + index77 + '][description]" required="required" class="svtext-right form-control" autocomplete="off" />' +
                            '</td>' +
                            '<td>' +
                            '<input type="text" id="guia_remision_destinatarios_' + index + '_items_' + index77 + '_quantity" name="guia_remision[destinatarios][' + index + '][items][' + index77 + '][quantity]" required="required" class="svtext-right form-control" autocomplete="off"  value="1" />' +
                            '</td>' +
                            '</tr>';

                        $("#invoice-like-items-destinatario-" + index).append(filaaux);

                        document.getElementById("guia_remision_destinatarios_" + index + "_items_" + index77 + "_description").value = descripcion;
                        document.getElementById("guia_remision_destinatarios_" + index + "_items_" + index77 + "_quantity").value = cantidad;
                        index77++;

                    }

                    let collectionHolderguia = $('#guiaremision-like-items tbody');
                    let filaauxguia = '<tr>' +
                        '<td>' +
                        '<a class="text-red" title="Está seguro de eliminar la fila seleccionada ?" href="#" onclick="eliminarItemGuiaConfirm(this);"><span class="glyphicon glyphicon-trash"></span></a>' +
                        '</td>' +
                        '<td class="col-md-6 "><input type="hidden" class="sv_dest_codigo" value="svdest' + index + '">' + document.getElementById("destinatario_customer_name").value + '</td>' +
                        '<td class="col-md-1 ">' + document.getElementById("destinatario_customer_identification").value + '</td>' +
                        '<td class="col-md-1 cell-align-center ">' + parseInt(tableRows.length) + '</td>' +
                        '<td class="col-md-1"> <button type="button" class="btn btn-info" onclick="editarItemGuia(' + index + ')"><span class="glyphicon glyphicon-edit"></span> Editar</button></td>' +
                        '</tr>';

                    collectionHolderguia.append(filaauxguia);

                    $('#invoice-like-items tbody').empty();
                    document.getElementById("formdestinatariosv").reset();

                });

            });

            var modalConfirm = function (callback) {

                $("#saveid").on("click", function () {
                    callback(true);
                    $("#modal-search").modal('hide');
                });

                $("#closeid").on("click", function () {
                    callback(false);
                    $("#modal-search").modal('hide');
                });

                $("#closeid1").on("click", function () {
                    callback(false);
                    $("#modal-search").modal('hide');
                });
            };

            modalConfirm(function (confirm) {
                if (confirm) {
                    /*e.preventDefault();*/
                    document.getElementById('paramBuscar').value = '';
                    let sibling = start.parentElement;

                    if (document.getElementById('modal-search-title').innerHTML === 'Productos') {

                        /*let prod = sibling.getElementsByTagName("td")[1];*/
                        let descripcion = sibling.getElementsByTagName("td")[2];
                        let stock = sibling.getElementsByTagName("td")[3];

                        let index = document.getElementById('indexId').value;
                        if (index === 'undefined' || index.length === 0)
                            index = 0;
                        else
                            index = index.replace('sv', '');

                        /*document.getElementById("invoice_items_" + index + "_product").value = prod.innerHTML;*/
                        document.getElementById("destinatario_items_" + index + "_description").value = descripcion.innerHTML;
                        document.getElementById("destinatario_items_" + index + "_quantity").value = 1;

                        document.getElementById("destinatario_items_" + index + "_quantity").focus();
                        document.getElementById("modal-destinatario").focus();

                    } else if (document.getElementById('modal-search-title').innerHTML === 'Clientes') {
                        let aux = sibling.getElementsByTagName("td")[1];
                        let aux1 = sibling.getElementsByTagName("td")[2];
                        let aux3 = sibling.getElementsByTagName("td")[3];
                        let aux4 = sibling.getElementsByTagName("td")[4];

                        document.getElementById("destinatario_customer_identification").value = aux.innerHTML;
                        document.getElementById("destinatario_customer_name").value = aux1.innerHTML;
                        document.getElementById("destinatario_customer_email").value = aux3.innerHTML;
                        document.getElementById("destinatario_dir_destino").value = aux4.innerHTML;

                        document.getElementById("modal-destinatario").focus();

                    } else if (document.getElementById('modal-search-title').innerHTML === 'Transportistas') {
                        let aux = sibling.getElementsByTagName("td")[1];
                        let aux1 = sibling.getElementsByTagName("td")[2];
                        let aux3 = sibling.getElementsByTagName("td")[3];
                        let aux4 = sibling.getElementsByTagName("td")[4];

                        document.getElementById("guia_remision_transportista_identification").value = aux.innerHTML;
                        document.getElementById("guia_remision_transportista_name").value = aux1.innerHTML;
                        document.getElementById("guia_remision_transportista_email").value = aux4.innerHTML;
                        document.getElementById("guia_remision_transportista_placa").value = aux3.innerHTML;

                        document.getElementById("guia_remision_transportista_name").focus();
                    }

                } else {


                }

                document.getElementById('post_data').innerHTML = '';
                document.getElementById('total_data').innerHTML = '';
                document.getElementById('pagination_link').innerHTML = '';
                document.getElementById('paramBuscar').dataset.table = '';
                document.getElementById("paramBuscar").placeholder = '';
            });

            document.addEventListener('keyup', function (e) {
                e.preventDefault();/*solo para disparar el evento en la busqueda modal de productos */

                if (e.target.className.indexOf('sv_table_data') !== -1 && e.type.indexOf('keyup') !== -1) {
                    e = e || window.event;
                    if (e.keyCode == '38') {/*// up arrow*/
                        let idx = start.cellIndex;
                        let nextrow = start.parentElement.previousElementSibling;
                        if (nextrow != null) {
                            let sibling = nextrow.cells[idx];
                            proddotheneedful(sibling);
                        }
                    } else if (e.keyCode == '40') {/* // down arrow*/
                        let idx = start.cellIndex;
                        let nextrow = start.parentElement.nextElementSibling;
                        if (nextrow != null) {
                            let sibling = nextrow.cells[idx];
                            proddotheneedful(sibling);
                        }/* } else if (e.keyCode == '37') { // left arrow var sibling = start.previousElementSibling; proddotheneedful(sibling); } else if (e.keyCode == '39') { // right arrow var sibling = start.nextElementSibling; proddotheneedful(sibling);*/
                    } else if (e.keyCode == '13') {/*// right arrow*/
                        start.parentElement.style.backgroundColor = '';
                        start.parentElement.style.color = '';
                        /*let sibling = start.parentElement;
                        let aux = sibling.getElementsByTagName("td")[1];
                        let aux1 = sibling.getElementsByTagName("td")[2];
                        document.getElementById('productoId').value = aux.innerHTML;
                        document.getElementById('productoDesc').value = aux1.innerHTML;*/
                        document.getElementById('saveid').click();
                        /*alert(sibling.innerHTML);*/
                    }
                }
            });

            function editarItemGuia(index) {

                document.getElementById("destinatario_customer_identification").value = document.getElementById("guia_remision_destinatarios_" + index + "_customer_identification").value;
                document.getElementById("destinatario_customer_name").value = document.getElementById("guia_remision_destinatarios_" + index + "_customer_name").value;
                document.getElementById("destinatario_customer_email").value = document.getElementById("guia_remision_destinatarios_" + index + "_customer_email").value;
                document.getElementById("destinatario_dir_destino").value = document.getElementById("guia_remision_destinatarios_" + index + "_dir_destino").value;
                document.getElementById("destinatario_motivoTraslado").value = document.getElementById("guia_remision_destinatarios_" + index + "_motivoTraslado").value;
                document.getElementById("destinatario_ruta").value = document.getElementById("guia_remision_destinatarios_" + index + "_ruta").value;
                document.getElementById("destinatario_motivoTraslado").value = document.getElementById("guia_remision_destinatarios_" + index + "_motivoTraslado").value;
                document.getElementById("destinatario_codEstabDestino").value = document.getElementById("guia_remision_destinatarios_" + index + "_codEstabDestino").value;
                document.getElementById("destinatario_docAduanero").value = document.getElementById("guia_remision_destinatarios_" + index + "_docAduanero").value;
                document.getElementById("destinatario_invoiceSerie").value = document.getElementById("guia_remision_destinatarios_" + index + "_invoiceSerie").value;
                document.getElementById("destinatario_invoiceNumero").value = document.getElementById("guia_remision_destinatarios_" + index + "_invoiceNumero").value;
                document.getElementById("destinatario_invoiceFecha").value = document.getElementById("guia_remision_destinatarios_" + index + "_invoiceFecha").value;
                document.getElementById("destinatario_invoiceAutorizacion").value = document.getElementById("guia_remision_destinatarios_" + index + "_invoiceAutorizacion").value;

                $('#invoice-like-items tbody').empty();

                $('#invoice-like-items-destinatario-' + index + ' tbody tr').each(function (tr, indexkey) {
                    let collectionHolder = $('#invoice-like-items tbody');
                    let prototype = collectionHolder.attr('data-prototype');
                    let index = svindex++;

                    form = prototype.replace(/__name__/g, index);
                    form = form.replace('class="edit-item-row"', 'id="sv' + index + '" class="edit-item-row"');
                    collectionHolder.append(form);

                    $(this).find('input').each(function () {
                        let input = $(this);
                        if (input.attr('id').includes('description'))
                            document.getElementById("destinatario_items_" + index + "_description").value = input.val();
                        else if (input.attr('id').includes('quantity'))
                            document.getElementById("destinatario_items_" + index + "_quantity").value = input.val();

                    });

                });

                $('#modal-destinatario').modal('show');
            }

            function tipodocumento(sender) {

                let maxlenght = 20;
                if (sender.value === '05') {
                    maxlenght = 10;
                } else if (sender.value === '04') {
                    maxlenght = 13;
                }
                document.getElementById("transportista_identification").maxLength = maxlenght;
            }

        </script>


    {% endblock %}

