{% extends "base.html.twig" %}

{% trans_default_domain 'core' %}

{% block actionheader %}
{% endblock %}

{% block searchform_container %}
{% endblock %}

{% block body %}

<div class="container-fluid">

    <div class="row">
        <div class="col-md-12">

            <div class="panel panel-primary">

                <div class="panel-heading">
                    <h3 class="panel-title">
                        <i class="glyphicon glyphicon-edit"></i>
                        Editar compra #{{ compra.id }}
                    </h3>
                </div>

                <div class="panel-body">

                     <form method="post"
                          action="{{ path('compras_actualizar', {'id': compra.id}) }}"
                          id="formCompra">

                        <input type="hidden"
                               name="_token"
                               value="{{ csrf_token('editar_compra_' ~ compra.id) }}">

                        <div class="row">

                            <!-- PROVEEDOR -->
                            <div class="col-md-4">

                                <div class="form-group">

                                    <label>Proveedor</label>

                                    <div class="input-group">

                                        <select name="provider_id"
                                                id="provider_id"
                                                class="form-control"
                                                required>

                                            <option value="">
                                                Seleccione un proveedor
                                            </option>

                                            {% for provider in providers %}

                                                <option value="{{ provider.id }}"
                                                        {% if compra.provider and compra.provider.id == provider.id %}selected{% endif %}>

                                                    {{ provider.name }}

                                                    {% if provider.identification %}
                                                        - {{ provider.identification }}
                                                    {% endif %}

                                                </option>

                                            {% endfor %}

                                        </select>

                                        <span class="input-group-btn">

                                            <button type="button"
                                                    class="btn btn-success"
                                                    data-toggle="modal"
                                                    data-target="#modalNuevoProveedor"
                                                    title="Nuevo proveedor">

                                                <span class="glyphicon glyphicon-plus"></span>

                                            </button>

                                        </span>

                                    </div>

                                </div>

                            </div>


                            <!-- FECHA -->
                            <div class="col-md-2">

                                <div class="form-group">

                                    <label>Fecha</label>

                                    <input type="date"
                                           name="fecha"
                                           class="form-control"
                                           value="{{ compra.fecha|date("Y-m-d") }}"
                                           required>

                                </div>

                            </div>


                            <!-- TIPO DOCUMENTO -->
                            <div class="col-md-2">

                                <div class="form-group">

                                    <label>Tipo documento</label>

                                    <select name="tipo_documento"
                                            class="form-control">

                                        <option value="01" {% if compra.tipoDocumento == '01' %}selected{% endif %}>
                                            Factura
                                        </option>

                                        <option value="03" {% if compra.tipoDocumento == '03' %}selected{% endif %}>
                                            Liquidación de compra
                                        </option>

                                        <option value="04" {% if compra.tipoDocumento == '04' %}selected{% endif %}>
                                            Nota de crédito
                                        </option>

                                        <option value="05" {% if compra.tipoDocumento == '05' %}selected{% endif %}>
                                            Nota de débito
                                        </option>

                                    </select>

                                </div>

                            </div>


                            <!-- SERIE -->
                            <div class="col-md-2">

                                <div class="form-group">

                                    <label>Serie</label>

                                    <input type="text"
                                           name="serie"
                                           class="form-control"
                                           placeholder="001-001"
                                           value="{{ compra.serie|default('') }}">

                                </div>

                            </div>


                            <!-- NUMERO -->
                            <div class="col-md-2">

                                <div class="form-group">

                                    <label>Número documento</label>

                                    <input type="text"
                                           name="numero_documento"
                                           class="form-control"
                                           placeholder="000000001"
                                           value="{{ compra.numeroDocumento }}"
                                           required>

                                </div>

                            </div>

                        </div>


                        <hr>


                        <h4>
                            Detalle de la compra
                        </h4>


                        <div class="table-responsive">

                            <table class="table table-bordered table-striped"
                                   id="tabla-detalle">

                                <thead>

                                    <tr>

                                        <th style="width:25%;">
                                            Producto
                                        </th>

                                        <th style="width:10%;">
                                            Cantidad
                                        </th>

                                        <th style="width:12%;">
                                            Precio unitario
                                        </th>

                                        <th style="width:10%;">
                                            Precio 2
                                        </th>

                                        <th style="width:10%;">
                                            Descuento ($)
                                        </th>

                                        <th style="width:8%;">
                                            Percha
                                        </th>

                                        <th style="width:8%;">
                                            Lote
                                        </th>

                                        <th style="width:10%;">
                                            Fecha caduca
                                        </th>

                                        <th style="width:12%;">
                                            Impuesto
                                        </th>

                                        <th style="width:8%;">
                                            Total
                                        </th>

                                        <th style="width:5%;">
                                            Acción
                                        </th>

                                    </tr>

                                </thead>


                                <tbody id="detalle-body">

{% for item in compra.items %}

    {% set existencia = null %}

    {% if item.product %}
        {% set existencia = item.product.inventarioExistencia %}
    {% endif %}

    <tr class="detalle-row">

       <!-- PRODUCTO -->
<td>

    <div class="input-group">

        <select name="producto[]"
                class="form-control producto-select"
                required>

            <option value="">
                Seleccione producto
            </option>

            {% for product in products %}

                <option value="{{ product.id }}"
                        data-descripcion="{{ product.description|e('html_attr') }}"
                        data-precio="{{ product.price }}"
                        data-precio2="{{ product.price2|default(0) }}"
                        {% if item.product and item.product.id == product.id %}selected{% endif %}>

                    {{ product.reference }}
                    -
                    {{ product.description }}

                </option>

            {% endfor %}

        </select>

        <span class="input-group-btn">

            <button type="button"
                    class="btn btn-success btn-nuevo-producto"
                    title="Nuevo producto">

                <span class="glyphicon glyphicon-plus"></span>

            </button>

        </span>

    </div>

</td>


        <!-- CANTIDAD -->
        <td>

            <input type="number"
                   name="cantidad[]"
                   class="form-control cantidad"
                   value="{{ item.cantidad|number_format(2, '.', '') }}"
                   min="0.01"
                   step="0.01"
                   required>

        </td>


        <!-- PRECIO -->
        <td>

            <input type="number"
                   name="precio_unitario[]"
                   class="form-control precio-unitario"
                   value="{{ item.precioUnitario|number_format(4, '.', '') }}"
                   min="0"
                   step="0.0001"
                   required>

        </td>


        <!-- PRECIO 2 -->
        <td>

            <input type="number"
                   name="precio2[]"
                   class="form-control precio2"
                   value="{{ item.product.price2|default(0)|number_format(4, '.', '') }}"
                   min="0"
                   step="0.0001">

        </td>


        <!-- DESCUENTO -->
        <td>

            <div class="input-group">

                <span class="input-group-addon">
                    $
                </span>

                <input type="number"
                       name="descuento[]"
                       class="form-control descuento"
                       value="{{ item.descuento }}"
                       min="0"
                       step="0.01">

            </div>

        </td>


        <!-- PERCHA -->
        <td>

            <input type="text"
                   name="percha[]"
                   class="form-control percha"
                   value="{% if existencia %}{{ existencia.percha|default('') }}{% endif %}">

        </td>


        <!-- LOTE -->
        <td>

            <input type="text"
                   name="lote[]"
                   class="form-control lote"
                   value="{% if existencia %}{{ existencia.lote|default('') }}{% endif %}">

        </td>


        <!-- FECHA CADUCA -->
        <td>

            <input type="date"
                   name="fecha_caduca[]"
                   class="form-control fecha-caduca"
                   value="{% if existencia and existencia.fechaCaduca %}{{ existencia.fechaCaduca|date('Y-m-d') }}{% endif %}">

        </td>


      <!-- IMPUESTO -->
<td>

    <select name="tax_id[]"
            class="form-control tax-select">

        <option value="">
            Sin impuesto
        </option>

        {% set impuestosMostrados = [] %}

        {# ===================================================== #}
        {# PRIMERO: MOSTRAR EL IMPUESTO ACTUAL DEL ITEM          #}
        {# ===================================================== #}

        {% if item.tax %}

            {% set taxActual = item.tax %}
            {% set claveActual = taxActual.codigoSri ~ '_' ~ taxActual.value %}

            <option value="{{ taxActual.id }}"
                    data-porcentaje="{{ taxActual.value }}"
                    data-codigo="{{ taxActual.codigoSri }}"
                    selected>

                {{ taxActual.name }} - {{ taxActual.value }}%

            </option>

            {% set impuestosMostrados = impuestosMostrados|merge([claveActual]) %}

        {% endif %}


        {# ===================================================== #}
        {# DESPUÉS: MOSTRAR SOLO IMPUESTOS ÚNICOS                #}
        {# ===================================================== #}

        {% for tax in taxes %}

            {% set claveImpuesto = tax.codigoSri ~ '_' ~ tax.value %}

            {% if claveImpuesto not in impuestosMostrados %}

                {% set impuestosMostrados = impuestosMostrados|merge([claveImpuesto]) %}

                <option value="{{ tax.id }}"
                        data-porcentaje="{{ tax.value }}"
                        data-codigo="{{ tax.codigoSri }}">

                    {{ tax.name }} - {{ tax.value }}%

                </option>

            {% endif %}

        {% endfor %}

    </select>

</td>


       <!-- TOTAL LINEA -->
<td style="min-width: 120px;">

    <input type="text"
           class="form-control total-linea"
           value="0.00"
           readonly
           style="min-width: 110px;">

</td>


        <!-- ELIMINAR -->
        <td>

            <button type="button"
                    class="btn btn-danger btn-sm eliminar-linea">

                <span class="glyphicon glyphicon-trash"></span>

            </button>

        </td>

    </tr>

{% endfor %}

</tbody>

                            </table>

                        </div>


                        <button type="button"
                                id="agregar-linea"
                                class="btn btn-default">

                            <span class="glyphicon glyphicon-plus"></span>

                            Agregar producto

                        </button>


                        <hr>


                        <!-- TOTALES -->
                        <div class="row">

                            <div class="col-md-4 col-md-offset-8">

                                <table class="table table-bordered">

                                    <tr>

                                        <th>
                                            Subtotal
                                        </th>

                                        <td>

                                            <input type="text"
                                                   id="subtotal"
                                                   class="form-control text-right"
                                                   value="0.00"
                                                   readonly>

                                        </td>

                                    </tr>


                                    <tr>

                                        <th>
                                            Descuento
                                        </th>

                                        <td>

                                            <input type="text"
                                                   id="descuento-total"
                                                   class="form-control text-right"
                                                   value="0.00"
                                                   readonly>

                                        </td>

                                    </tr>


                                    <tr>

                                        <th>
                                            Base IVA
                                        </th>

                                        <td>

                                            <input type="text"
                                                   id="base-iva"
                                                   class="form-control text-right"
                                                   value="0.00"
                                                   readonly>

                                        </td>

                                    </tr>


                                    <tr>

                                        <th>
                                            IVA
                                        </th>

                                        <td>

                                            <input type="text"
                                                   id="iva"
                                                   class="form-control text-right"
                                                   value="0.00"
                                                   readonly>

                                        </td>

                                    </tr>


                                    <tr>

                                        <th>
                                            Total
                                        </th>

                                        <td>

                                            <input type="text"
                                                   id="total"
                                                   class="form-control text-right"
                                                   value="0.00"
                                                   readonly>

                                        </td>

                                    </tr>

                                </table>

                            </div>

                        </div>


                        <!-- OBSERVACION -->
                        <div class="form-group">

                            <label>
                                Observación
                            </label>

                            <textarea name="observacion"
                                      class="form-control"
                                      rows="3">{{ compra.observacion|default('') }}</textarea>

                        </div>


                        <!-- BOTONES -->
                        <div class="text-right">

                            <a href="{{ path('compras_index') }}"
                               class="btn btn-default">

                                <span class="glyphicon glyphicon-arrow-left"></span>

                                Cancelar

                            </a>

                            <button type="submit"
                                    class="btn btn-primary">

                                <span class="glyphicon glyphicon-save"></span>

                                Guardar cambios

                            </button>

                        </div>

                    </form>

                </div>

            </div>

        </div>
    </div>

</div>


<!-- ========================================================= -->
<!-- MODAL NUEVO PROVEEDOR -->
<!-- ========================================================= -->

<div class="modal fade"
     id="modalNuevoProveedor"
     tabindex="-1"
     role="dialog"
     aria-labelledby="modalNuevoProveedorLabel">

    <div class="modal-dialog"
         role="document">

        <div class="modal-content">


            <!-- HEADER -->
            <div class="modal-header">

                <button type="button"
                        class="close"
                        data-dismiss="modal"
                        aria-label="Cerrar">

                    <span aria-hidden="true">
                        &times;
                    </span>

                </button>

                <h4 class="modal-title"
                    id="modalNuevoProveedorLabel">

                    <span class="glyphicon glyphicon-user"></span>

                    Nuevo proveedor

                </h4>

            </div>


            <!-- FORMULARIO -->
            <form id="formNuevoProveedor">

                <div class="modal-body">


                    <!-- NOMBRE -->
                    <div class="form-group">

                        <label>
                            Nombre / Razón social
                        </label>

                        <input type="text"
                               name="name"
                               id="nuevo_provider_name"
                               class="form-control"
                               required>

                    </div>


                    <div class="row">


                        <!-- IDENTIFICACION -->
                        <div class="col-md-6">

                            <div class="form-group">

                                <label>
                                    Identificación / RUC
                                </label>

                                <input type="text"
                                       name="identification"
                                       id="nuevo_provider_identification"
                                       class="form-control">

                            </div>

                        </div>


                        <!-- TIPO DOCUMENTO -->
                        <div class="col-md-6">

                            <div class="form-group">

                                <label>
                                    Tipo documento
                                </label>

                                <select name="tipo_documento"
                                        id="nuevo_provider_tipo_documento"
                                        class="form-control">

                                    <option value="">
                                        Seleccione
                                    </option>

                                    <option value="04">
                                        RUC
                                    </option>

                                    <option value="05">
                                        Cédula
                                    </option>

                                    <option value="06">
                                        Pasaporte
                                    </option>

                                    <option value="07">
                                        Consumidor final
                                    </option>

                                </select>

                            </div>

                        </div>

                    </div>


                    <div class="row">


                        <!-- EMAIL -->
                        <div class="col-md-6">

                            <div class="form-group">

                                <label>
                                    Email
                                </label>

                                <input type="email"
                                       name="email"
                                       id="nuevo_provider_email"
                                       class="form-control">

                            </div>

                        </div>


                        <!-- TELEFONO -->
                        <div class="col-md-6">

                            <div class="form-group">

                                <label>
                                    Teléfono
                                </label>

                                <input type="text"
                                       name="telefono"
                                       id="nuevo_provider_telefono"
                                       class="form-control">

                            </div>

                        </div>

                    </div>


                    <!-- DIRECCION -->
                    <div class="form-group">

                        <label>
                            Dirección
                        </label>

                        <input type="text"
                               name="address"
                               id="nuevo_provider_address"
                               class="form-control">

                    </div>


                    <!-- TIPO PROVEEDOR -->
                    <div class="form-group">

                        <label>
                            Tipo de proveedor
                        </label>

                        <select name="tipo_proveedor"
                                id="nuevo_provider_tipo_proveedor"
                                class="form-control">

                            <option value="">
                                Seleccione
                            </option>

                            <option value="01">
                                Bienes
                            </option>

                            <option value="02">
                                Servicios
                            </option>

                            <option value="03">
                                Bienes y servicios
                            </option>

                        </select>

                    </div>


                    <!-- MENSAJE -->
                    <div id="mensaje-nuevo-proveedor"
                         class="alert"
                         style="display:none;">
                    </div>

                </div>


                <!-- FOOTER -->
                <div class="modal-footer">

                    <button type="button"
                            class="btn btn-default"
                            data-dismiss="modal">

                        Cancelar

                    </button>

                    <button type="submit"
                            id="guardar-nuevo-proveedor"
                            class="btn btn-success">

                        <span class="glyphicon glyphicon-save"></span>

                        Guardar proveedor

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>

<!-- ========================================================= -->
<!-- MODAL NUEVO PRODUCTO -->
<!-- ========================================================= -->

<div class="modal fade"
     id="modalNuevoProducto"
     tabindex="-1"
     role="dialog"
     aria-labelledby="modalNuevoProductoLabel">

    <div class="modal-dialog" role="document">

        <div class="modal-content">

            <form id="formNuevoProducto">

                <input type="hidden"
                       name="_token"
                       value="{{ csrf_token('nuevo_producto_compra') }}">

                <div class="modal-header">

                    <button type="button"
                            class="close"
                            data-dismiss="modal"
                            aria-label="Cerrar">

                        <span aria-hidden="true">&times;</span>

                    </button>

                    <h4 class="modal-title"
                        id="modalNuevoProductoLabel">

                        Nuevo producto

                    </h4>

                </div>


                <div class="modal-body">

                    <div id="producto-error"
                         class="alert alert-danger"
                         style="display:none;">
                    </div>

                    <div id="producto-success"
                         class="alert alert-success"
                         style="display:none;">
                    </div>


                    <!-- REFERENCIA -->
                    <div class="form-group">

                        <label for="producto_reference">
                            Codigo
                        </label>

                        <input type="text"
                               id="producto_reference"
                               name="reference"
                               class="form-control"
                               maxlength="25"
                               required>

                    </div>


                    <!-- DESCRIPCIÓN -->
                    <div class="form-group">

                        <label for="producto_description">
                            Descripción
                        </label>

                        <input type="text"
                               id="producto_description"
                               name="description"
                               class="form-control"
                               maxlength="255"
                               required>

                    </div>


                    <!-- PRECIO -->
                    <div class="form-group">

                        <label for="producto_price">
                            Precio de compra
                        </label>

                        <div class="input-group">

                            <span class="input-group-addon">
                                $
                            </span>

                            <input type="number"
                                   id="producto_price"
                                   name="price"
                                   class="form-control"
                                   value="0"
                                   min="0"
                                   step="0.000001"
                                   required>

                        </div>

                    </div>


                    <!-- IMPUESTO -->
                    <div class="form-group">

                        <label for="producto_tax_id">
                            Impuesto
                        </label>

                        <select id="producto_tax_id"
        name="tax_id"
        class="form-control">

    <option value="">
        Sin impuesto
    </option>

    {% set porcentajesIva = {} %}

    {% for tax in taxes %}

        {% set porcentaje = tax.value|number_format(2, '.', '') %}

        {% if porcentajesIva[porcentaje] is not defined %}

            {% set porcentajesIva = porcentajesIva|merge({
                (porcentaje): tax
            }) %}

        {% endif %}

    {% endfor %}

    {% for porcentaje, tax in porcentajesIva %}

        <option value="{{ tax.id }}"
                data-porcentaje="{{ tax.value }}"
                data-codigo="{{ tax.codigoSri }}">

            {{ tax.name }} - {{ tax.value }}%

        </option>

    {% endfor %}

</select>

                    </div>

                </div>


                <div class="modal-footer">

                    <button type="button"
                            class="btn btn-default"
                            data-dismiss="modal">

                        Cancelar

                    </button>

                    <button type="submit"
                            class="btn btn-success"
                            id="btnGuardarProducto">

                        <span class="glyphicon glyphicon-floppy-disk"></span>
                        Guardar producto

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>


<script>

$(document).ready(function () {

    /*
     * =========================================================
     * FILA DONDE SE PRESIONÓ NUEVO PRODUCTO
     * =========================================================
     */

    window.filaProductoNueva = null;


    /*
     * =========================================================
     * ABRIR MODAL
     * =========================================================
     */

    $(document).on('click', '.btn-nuevo-producto', function () {

        window.filaProductoNueva = $(this).closest('.detalle-row');


        /*
         * Limpiar formulario
         */

        $('#formNuevoProducto')[0].reset();


        /*
         * Limpiar mensajes
         */

        $('#producto-error')
            .hide()
            .html('');

        $('#producto-success')
            .hide()
            .html('');


        /*
         * Mostrar modal
         */

        $('#modalNuevoProducto').modal('show');

    });


    /*
     * =========================================================
     * GUARDAR PRODUCTO
     * =========================================================
     */

    $('#formNuevoProducto').on('submit', function (e) {

        e.preventDefault();


        var formulario = $(this);

        var boton = $('#btnGuardarProducto');


        /*
         * Deshabilitar botón
         */

        boton.prop('disabled', true);


        /*
         * Limpiar mensajes
         */

        $('#producto-error')
            .hide()
            .html('');

        $('#producto-success')
            .hide()
            .html('');


        /*
         * AJAX
         */

        $.ajax({

            url: '{{ path("compras_nuevo_producto") }}',

            type: 'POST',

            data: formulario.serialize(),

            dataType: 'json',


            /*
             * =================================================
             * ÉXITO
             * =================================================
             */

            success: function (respuesta) {


                if (!respuesta.success) {

                    $('#producto-error')
                        .html(respuesta.message || 'No se pudo crear el producto.')
                        .show();

                    boton.prop('disabled', false);

                    return;
                }


                var producto = respuesta.product;


                /*
                 * =================================================
                 * AGREGAR PRODUCTO A TODOS LOS SELECT
                 * =================================================
                 */

                $('.producto-select').each(function () {

                    var select = $(this);


                    if (
                        select.find(
                            'option[value="' + producto.id + '"]'
                        ).length === 0
                    ) {

                        var option = $('<option></option>');

                        option
                            .val(producto.id)
                            .attr(
                                'data-descripcion',
                                producto.description
                            )
                            .attr(
                                'data-precio',
                                producto.price
                            )
                            .attr(
                                'data-precio2',
                                producto.price2 || 0
                            )
                            .text(
                                producto.reference +
                                ' - ' +
                                producto.description
                            );

                        select.append(option);

                    }

                });


                /*
                 * =================================================
                 * SELECCIONAR EN LA FILA ACTUAL
                 * =================================================
                 */

                var filaDestino =
                    window.filaProductoNueva || null;


                if (filaDestino) {

                    var selectDestino =
                        filaDestino.find('.producto-select');


                    /*
                     * Seleccionar producto
                     */

                    selectDestino
                        .val(producto.id)
                        .trigger('change');


                    /*
                     * Colocar precio
                     */

                    filaDestino
                        .find('.precio-unitario')
                        .val(producto.price);


                    /*
                     * Colocar Precio 2
                     */

                    filaDestino
                        .find('.precio2')
                        .val(producto.price2 || 0);


                    /*
                     * Colocar impuesto
                     */

                    if (
                        producto.tax_id !== null &&
                        producto.tax_id !== ''
                    ) {

                        filaDestino
                            .find('.tax-select')
                            .val(producto.tax_id)
                            .trigger('change');

                    }

                }


                /*
                 * =================================================
                 * RECALCULAR
                 * =================================================
                 */

                if (typeof calcularTotales === 'function') {

                    calcularTotales();

                }


                /*
                 * =================================================
                 * MENSAJE
                 * =================================================
                 */

                $('#producto-success')
                    .html(
                        respuesta.message ||
                        'Producto creado correctamente.'
                    )
                    .show();


                /*
                 * Cerrar modal
                 */

                setTimeout(function () {

                    $('#modalNuevoProducto').modal('hide');

                }, 700);


                boton.prop('disabled', false);

            },


            /*
             * =================================================
             * ERROR
             * =================================================
             */

            error: function (xhr) {

                var mensaje =
                    'Ocurrió un error al crear el producto.';


                if (
                    xhr.responseJSON &&
                    xhr.responseJSON.message
                ) {

                    mensaje =
                        xhr.responseJSON.message;

                }


                $('#producto-error')
                    .html(mensaje)
                    .show();


                boton.prop('disabled', false);

            }

        });

    });

});

</script>

<script>

$(document).ready(function () {


    /*
     * ========================================================
     * SELECCIONAR PRODUCTO
     * ========================================================
     */

    $(document).on('change', '.producto-select', function () {

        var option = $(this).find('option:selected');

        var precio = option.data('precio');
        var precio2 = option.data('precio2');

        if (precio !== undefined) {

            $(this)
                .closest('.detalle-row')
                .find('.precio-unitario')
                .val(precio);

        }

        if (precio2 !== undefined) {

            $(this)
                .closest('.detalle-row')
                .find('.precio2')
                .val(precio2);

        }

        calcularTotales();

    });


    /*
     * ========================================================
     * AGREGAR NUEVA LINEA
     * ========================================================
     */

    $('#agregar-linea').on('click', function () {

        var fila = $('.detalle-row:first').clone();

        fila.find('select').val('');
        fila.find('.cantidad').val('1');
        fila.find('.precio-unitario').val('0');
        fila.find('.precio2').val('0');
        fila.find('.descuento').val('0');
        fila.find('.percha').val('');
        fila.find('.lote').val('');
        fila.find('.fecha-caduca').val('');
        fila.find('.total-linea').val('0.00');

        $('#detalle-body').append(fila);

        calcularTotales();

    });


    /*
     * ========================================================
     * ELIMINAR LINEA
     * ========================================================
     */

    $(document).on('click', '.eliminar-linea', function () {

        if ($('.detalle-row').length <= 1) {

            var fila = $(this).closest('.detalle-row');

            fila.find('select').val('');
            fila.find('.cantidad').val('1');
            fila.find('.precio-unitario').val('0');
            fila.find('.precio2').val('0');
            fila.find('.descuento').val('0');
            fila.find('.percha').val('');
            fila.find('.lote').val('');
            fila.find('.fecha-caduca').val('');

            calcularTotales();

            return;
        }

        $(this).closest('.detalle-row').remove();

        calcularTotales();

    });


    /*
     * ========================================================
     * RECALCULAR TOTALES
     *
     * EL DESCUENTO ES DIRECTAMENTE EN DOLARES
     * ========================================================
     */

    $(document).on(
        'keyup change',
        '.cantidad, .precio-unitario, .descuento, .tax-select',
        function () {

            calcularTotales();

        }
    );


    /*
     * ========================================================
     * CALCULO DE TOTALES
     * ========================================================
     */

    function calcularTotales() {

        var subtotal = 0;
        var descuentoTotal = 0;
        var baseIva = 0;
        var iva = 0;


        $('.detalle-row').each(function () {

            var fila = $(this);


            var cantidad =
                parseFloat(fila.find('.cantidad').val()) || 0;


            var precio =
                parseFloat(fila.find('.precio-unitario').val()) || 0;


            /*
             * DESCUENTO DIRECTO EN DOLARES
             */
            var descuento =
                parseFloat(fila.find('.descuento').val()) || 0;


            var tax =
                fila.find('.tax-select option:selected');


            var porcentaje =
                parseFloat(tax.data('porcentaje')) || 0;


            /*
             * BRUTO
             */
            var bruto =
                cantidad * precio;


            /*
             * DESCUENTO NO PUEDE SUPERAR EL BRUTO
             */
            if (descuento > bruto) {

                descuento = bruto;

                fila.find('.descuento')
                    .val(descuento.toFixed(2));

            }


            /*
             * BASE DESPUES DEL DESCUENTO
             */
            var base =
                bruto - descuento;


            if (base < 0) {
                base = 0;
            }


            /*
             * IVA
             */
            var ivaLinea =
                base * porcentaje / 100;


            /*
             * TOTAL LINEA
             */
            var totalLinea =
                base + ivaLinea;


            subtotal += bruto;

            descuentoTotal += descuento;


            if (porcentaje > 0) {

                baseIva += base;

            }


            iva += ivaLinea;


            fila.find('.total-linea')
                .val(totalLinea.toFixed(2));

        });


        /*
         * TOTAL GENERAL
         */
        var total =
            subtotal - descuentoTotal + iva;


        $('#subtotal')
            .val(subtotal.toFixed(2));


        $('#descuento-total')
            .val(descuentoTotal.toFixed(2));


        $('#base-iva')
            .val(baseIva.toFixed(2));


        $('#iva')
            .val(iva.toFixed(2));


        $('#total')
            .val(total.toFixed(2));

    }


    /*
     * ========================================================
     * NUEVO PROVEEDOR
     * ========================================================
     */

    $('#formNuevoProveedor').on('submit', function (e) {

        e.preventDefault();


        var formulario = $(this);

        var boton = $('#guardar-nuevo-proveedor');

        var mensaje = $('#mensaje-nuevo-proveedor');


        /*
         * LIMPIAR MENSAJE
         */
        mensaje
            .hide()
            .removeClass('alert-success alert-danger')
            .html('');


        /*
         * DESACTIVAR BOTON
         */
        boton.prop('disabled', true);

        boton.html(
            '<span class="glyphicon glyphicon-refresh"></span> Guardando...'
        );


        /*
         * ENVIAR AL CONTROLADOR
         */
        $.ajax({

            url: "{{ path('compras_nuevo_proveedor') }}",

            type: "POST",

            data: formulario.serialize(),

            dataType: "json",

            success: function (respuesta) {


                if (!respuesta.success) {

                    mensaje
                        .addClass('alert-danger')
                        .html(respuesta.message)
                        .show();

                    boton.prop('disabled', false);

                    boton.html(
                        '<span class="glyphicon glyphicon-save"></span> Guardar proveedor'
                    );

                    return;

                }


                /*
                 * DATOS DEL NUEVO PROVEEDOR
                 */
                var proveedor =
                    respuesta.provider;


                /*
                 * CREAR OPTION
                 */
                var option =
                    $('<option></option>')
                        .attr('value', proveedor.id)
                        .text(
                            proveedor.name +
                            (
                                proveedor.identification
                                    ? ' - ' + proveedor.identification
                                    : ''
                            )
                        );


                /*
                 * AGREGAR AL SELECT
                 */
                $('#provider_id')
                    .append(option)
                    .val(proveedor.id);


                /*
                 * MENSAJE
                 */
                mensaje
                    .removeClass('alert-danger')
                    .addClass('alert-success')
                    .html(respuesta.message)
                    .show();


                /*
                 * CERRAR MODAL
                 */
                setTimeout(function () {

                    $('#modalNuevoProveedor')
                        .modal('hide');


                    /*
                     * LIMPIAR FORMULARIO
                     */
                    formulario[0].reset();


                    mensaje.hide();

                }, 700);


            },


            error: function (xhr) {

                var respuesta = xhr.responseJSON;


                var texto =
                    (
                        respuesta &&
                        respuesta.message
                    )
                        ? respuesta.message
                        : 'No se pudo guardar el proveedor.';


                mensaje
                    .removeClass('alert-success')
                    .addClass('alert-danger')
                    .html(texto)
                    .show();


            },


            complete: function () {

                boton.prop('disabled', false);

                boton.html(
                    '<span class="glyphicon glyphicon-save"></span> Guardar proveedor'
                );

            }

        });

    });


    /*
     * ========================================================
     * CALCULAR AL CARGAR
     * ========================================================
     */

    calcularTotales();

});

</script>

{% endblock %}