{% 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-shopping-cart"></i>
                        Nueva compra
                    </h3>
                </div>

                <div class="panel-body">

                     <form method="post" action="{{ path('compras_guardar') }}" id="formCompra">

                        <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 }}">

                                                    {{ 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="{{ "now"|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">
                                            Factura
                                        </option>

                                        <option value="03">
                                            Liquidación de compra
                                        </option>

                                        <option value="04">
                                            Nota de crédito
                                        </option>

                                        <option value="05">
                                            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">

                                </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"
                                           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:22%;">
                                            Producto
                                        </th>

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

                                        <th style="width:9%;">
                                            Precio 1
                                        </th>

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

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

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

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

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

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

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

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

                                    </tr>

                                </thead>


                                <tbody id="detalle-body">

                                    <tr class="detalle-row">


                                        <!-- PRODUCTO -->
                                        <td>

                                            <div class="input-group">

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

                                                    <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.precio2|default(0) }}">

                                                            {{ 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="1.00"
                                                   min="0.01"
                                                   step="0.01">

                                        </td>


                                        <!-- PRECIO 1 -->
                                        <td>

                                            <input type="number"
                                                   name="precio_unitario[]"
                                                   class="form-control precio-unitario"
                                                   value="0.0000"
                                                   min="0"
                                                   step="0.0001">

                                        </td>


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

                                            <input type="number"
                                                   name="precio2[]"
                                                   class="form-control precio2"
                                                   value="0.0000"
                                                   min="0"
                                                   step="0.0001">

                                        </td>


                                        <!-- DESCUENTO EN DOLARES -->
                                        <td>

                                            <div class="input-group">

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

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

                                            </div>

                                        </td>


                                        <!-- IMPUESTO -->
                                        <td>

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

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

                                                {% for tax in taxes %}

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

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

                                                    </option>

                                                {% endfor %}

                                            </select>

                                        </td>


                                        <!-- PERCHA -->
                                        <td>

                                            <input type="text"
                                                   name="percha[]"
                                                   class="form-control percha"
                                                   value=""
                                                   maxlength="100">

                                        </td>


                                        <!-- LOTE -->
                                        <td>

                                            <input type="text"
                                                   name="lote[]"
                                                   class="form-control lote"
                                                   value=""
                                                   maxlength="100">

                                        </td>


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

                                            <input type="date"
                                                   name="fecha_caduca[]"
                                                   class="form-control fecha-caduca"
                                                   value="">

                                        </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"
                                                    title="Eliminar">

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

                                            </button>

                                        </td>

                                    </tr>

                                </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"></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 compra

                            </button>

                        </div>

                    </form>

                </div>

            </div>

        </div>
    </div>

</div>


<!-- ============================================================
     MODAL IMPORTAR COMPRA DESDE EXCEL
     ============================================================ -->

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

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

        <div class="modal-content">

            <form method="post"
                  action="{{ path('compras_importar') }}"
                  enctype="multipart/form-data"
                  id="formImportarExcel">

                <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="modalImportarExcelLabel">
                        Importar compra desde Excel
                    </h4>

                </div>


                <div class="modal-body">

                    <div class="alert alert-info">

                        <strong>Datos generales de la compra</strong><br>

                        Seleccione el proveedor e ingrese los datos del comprobante.
                        Estos datos se aplicarán a toda la compra importada.

                    </div>


                    <div class="row">

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

                            <div class="form-group">

                                <label for="provider_id_importacion">
                                    Proveedor
                                </label>

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

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

                                    {% for provider in providers %}

                                        <option value="{{ provider.id }}"
                                                data-ruc="{{ provider.identification|default('') }}">

                                            {{ provider.name }}

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

                                        </option>

                                    {% endfor %}

                                </select>

                            </div>

                        </div>


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

                            <div class="form-group">

                                <label for="ruc_proveedor">
                                    RUC / Identificación
                                </label>

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

                            </div>

                        </div>

                    </div>


                    <div class="row">

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

                            <div class="form-group">

                                <label for="fecha_importacion">
                                    Fecha
                                </label>

                                <input type="date"
                                       name="fecha"
                                       id="fecha_importacion"
                                       class="form-control"
                                       value="{{ 'now'|date('Y-m-d') }}"
                                       required>

                            </div>

                        </div>


                        <!-- TIPO -->
                        <div class="col-md-3">

                            <div class="form-group">

                                <label for="tipo_importacion">
                                    Tipo de documento
                                </label>

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

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

                                    <option value="01">
                                        01 - Factura
                                    </option>

                                    <option value="03">
                                        03 - Liquidación de compra
                                    </option>

                                    <option value="04">
                                        04 - Nota de crédito
                                    </option>

                                    <option value="05">
                                        05 - Nota de débito
                                    </option>

                                </select>

                            </div>

                        </div>


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

                            <div class="form-group">

                                <label for="serie_importacion">
                                    Serie
                                </label>

                                <input type="text"
                                       name="serie"
                                       id="serie_importacion"
                                       class="form-control"
                                       placeholder="001-001"
                                       required>

                            </div>

                        </div>


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

                            <div class="form-group">

                                <label for="numero_importacion">
                                    Número
                                </label>

                                <input type="text"
                                       name="numero"
                                       id="numero_importacion"
                                       class="form-control"
                                       placeholder="000000001"
                                       required>

                            </div>

                        </div>

                    </div>


                    <hr>


                    <div class="alert alert-warning">

                        <strong>Archivo Excel</strong><br>

                        El archivo debe contener únicamente los productos de la compra.
                        Los datos generales se ingresan arriba.

                    </div>


                    <div class="form-group">

                        <label for="archivo_importacion">
                            Archivo Excel
                        </label>

                        <input type="file"
                               name="archivo"
                               id="archivo_importacion"
                               class="form-control"
                               accept=".xlsx,.xls"
                               required>

                    </div>


                    <div class="well well-sm">

                        <strong>Columnas del Excel:</strong>

                        <div class="table-responsive" style="margin-top:10px;">

                            <table class="table table-bordered table-condensed">

                                <thead>

                                    <tr>

                                        <th>CODIGO</th>
                                        <th>NOMBRE</th>
                                        <th>CANTIDAD</th>
                                        <th>PRECIO</th>
                                        <th>PRECIO2</th>
                                        <th>IVA</th>
                                        <th>PERCHA</th>
                                        <th>LOTE</th>
                                        <th>FECHA CADUCA</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <tr>

                                        <td>PROD001</td>
                                        <td>Producto de ejemplo</td>
                                        <td>5</td>
                                        <td>10.00</td>
                                        <td>12.00</td>
                                        <td>15</td>
                                        <td>A-01</td>
                                        <td>LOTE001</td>
                                        <td>31/12/2027</td>

                                    </tr>

                                </tbody>

                            </table>

                        </div>

                        <p class="text-muted">

                            <strong>PRECIO</strong> y <strong>PRECIO2</strong>
                            se ingresan sin IVA.

                            <br>

                            No se utiliza descuento en esta importación.

                        </p>

                    </div>


                    <!-- CSRF -->
                    <input type="hidden"
                           name="_token"
                           value="{{ csrf_token('importar_compra_excel') }}">


                </div>


                <div class="modal-footer">

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

                        Descargar plantilla Excel

                    </a>


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

                        Cancelar

                    </button>


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

                        <span class="glyphicon glyphicon-import"></span>
                        Importar compra

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>




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

<!-- 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>

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

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

        <div class="modal-content">

            <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">

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

                    Nuevo producto

                </h4>

            </div>


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

                <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>


                    <!-- DESCRIPCION -->

                    <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>

                            {% for tax in taxes %}

                                <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">

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

                        Cancelar

                    </button>


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

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

                        Guardar producto

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>


<script>

$(document).ready(function () {


    /*
     * ========================================================
     * NUEVO PRODUCTO
     * ========================================================
     */

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

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

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

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

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

        $('#btnGuardarProducto')
            .prop('disabled', false)
            .html(
                '<span class="glyphicon glyphicon-save"></span> ' +
                'Guardar producto'
            );

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

    });


    /*
     * ========================================================
     * GUARDAR NUEVO PRODUCTO POR AJAX
     * ========================================================
     */

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

        e.preventDefault();


        var formulario = $(this);

        var boton = $('#btnGuardarProducto');


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

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


        boton
            .prop('disabled', true)
            .html(
                '<span class="glyphicon glyphicon-refresh glyphicon-spin"></span> ' +
                'Guardando...'
            );


        $.ajax({

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

            type: 'POST',

            data: formulario.serialize(),

            dataType: 'json',

            success: function (respuesta) {


                if (!respuesta.success) {

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

                    boton
                        .prop('disabled', false)
                        .html(
                            '<span class="glyphicon glyphicon-save"></span> ' +
                            'Guardar producto'
                        );

                    return;

                }


                /*
                 * ============================================
                 * PRODUCTO CREADO
                 * ============================================
                 */

                var producto = respuesta.product;


                /*
                 * Agregamos el producto a TODOS los
                 * select de productos existentes.
                 */

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

                    var select = $(this);


                    /*
                     * Evitar duplicados si por alguna razón
                     * ya existe.
                     */

                    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
                            )
                            .text(
                                producto.reference +
                                ' - ' +
                                producto.description
                            );

                        select.append(option);

                    }

                });


                /*
                 * Seleccionar automáticamente el producto
                 * en la fila desde donde se abrió el modal.
                 */

                var filaDestino =
                    window.filaProductoNueva || null;


                if (filaDestino) {

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


                    /*
                     * Seleccionamos el producto nuevo.
                     */

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


                    /*
                     * Colocar precio automáticamente.
                     */

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


                    /*
                     * Seleccionar impuesto.
                     */

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

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

                    }

                }


                calcularTotales();


                /*
                 * Mostrar mensaje de éxito.
                 */

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


                /*
                 * Cerrar modal después de un momento.
                 */

                setTimeout(function () {

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

                }, 700);


                boton
                    .prop('disabled', false)
                    .html(
                        '<span class="glyphicon glyphicon-save"></span> ' +
                        'Guardar producto'
                    );


            },

            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)
                    .html(
                        '<span class="glyphicon glyphicon-save"></span> ' +
                        'Guardar producto'
                    );

            }

        });

    });





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

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

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

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

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


        if (precio !== undefined) {

            fila
                .find('.precio-unitario')
                .val(precio);

        }


        if (precio2 !== undefined) {

            fila
                .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>



<script>

$(document).ready(function () {

    /*
     * PROVEEDOR DE LA IMPORTACIÓN
     *
     * Al seleccionar el proveedor,
     * obtenemos automáticamente su identificación/RUC.
     */

    $('#provider_id_importacion').on('change', function () {

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

        var ruc = optionSeleccionada.attr('data-ruc') || '';

        $('#ruc_proveedor').val(ruc);

    });


    /*
     * AL CERRAR EL MODAL
     *
     * Limpiamos los datos para que la siguiente
     * importación empiece nuevamente.
     */

    $('#modalImportarExcel').on('hidden.bs.modal', function () {

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

        $('#ruc_proveedor').val('');

        $('#fecha_importacion').val(
            new Date().toISOString().split('T')[0]
        );

    });

});

</script>

{% endblock %}