@extends('layout.main')
@section('contenido')
    <form action="{{ url('/compra') }}" method="post">
        @csrf
        {{-- mensaje de restricción --}}
        @if (count($errors) > 0)
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        @if(Session::has('no_det'))
            <div class="alert alert-danger alert-dismissible fade show mb-2 mt-2" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                <strong>Compra restringida! </strong>{{Session::get('no_det')}}
            </div>
        @endif
        <div class="card">
            <div class="card-header">
                <h4>Registrar Compra</h4>
            </div>
            <div class="card-body">
                <div class="row align-items-start">
                    <div class="col-2 mb-2 mt-2">
                        {{-- <div class="form-floating"> --}}
                        <label for="floatingInput" class="mb-1"><strong>Fecha</strong></label>
                        <input type="date" class="form-control form-control-sm" name="fecha" id="fecha" <input type="date"
                            class="form-control" value="{{ $date['0']->fecha }}" name="fecha" id="fecha"
                            autocomplete="off" placeholder="fecha">
                        {{-- </div> --}}
                    </div>
                    <div class="col-2 mb-2 mt-2">
                        {{-- <div class="form-floating"> --}}
                        <label for="floatingInput" class="mb-1"><strong>Condición</strong></label>
                        <select name="condicion" id="condicion" class="form-control form-control-sm">
                            <option value="CONTADO">CONTADO</option>
                            <option value="CREDITO">CREDITO</option>
                        </select>
                        {{-- </div> --}}
                    </div>
                    <div class="col-2 mb-2 mt-2">
                        {{-- <div class="form-floating"> --}}
                        <label for="floatingInput" class="mb-1"><strong>Factura N°</strong></label>
                        <input type="text" class="form-control form-control-sm" required name="fact_nro" id="fact_nro" autocomplete="off"
                            placeholder="Factura Nº">
                        {{-- </div> --}}
                    </div>
                    {{-- <div class="col-2 mb-2 mt-2">
                        
                        <label for="floatingInput" class="mb-1"><strong>Depósito</strong></label>
                        <select name="iddeposito" id="iddeposito" class="form-control">
                            @foreach ($depositos as $deposito)
                                <option value="{{ $deposito['iddeposito'] }}">{{ $deposito['descripcion'] }}</option>
                            @endforeach
                        </select>
                        
                    </div> --}}
                    <div class="col-4 mb-2 mt-2">
                        {{-- <div class="form-floating"> --}}
                        <label for="floatingInput" class="mb-1"><strong>Proveedor</strong></label>
                        <select name="idproveedor" id="idproveedor" class="form-control">
                            @foreach ($proveedores as $proveedor)
                                <option value="{{ $proveedor['idproveedor'] }}">{{ $proveedor['denominacion'] }}
                                </option>
                            @endforeach
                        </select>
                        {{-- </div> --}}
                    </div>
                    <script>
                        $(document).ready(function() {
                            $('#idproveedor').select2();
                        });
                    </script>
                </div>
            </div>
        </div>
        {{-- <input type="hidden" name="objet_detalle" id="objet_detalle"> --}}
        <div class="card mb-2">
            <div class="card-header">
                <h4 class="card-title">Detalle de Compra</h4>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-4">
                        <label for="floatingInput" class="mb-1"><strong>Artículo</strong></label>
                        <select id="idarticulo" class="form-control">
                            @foreach ($articulos as $articulo)
                                <option value="{{ $articulo['idarticulo'] }}">
                                    {{ $articulo['nombre'] }}</option>
                            @endforeach
                        </select>
                    </div>
                    <script>
                        $(document).ready(function() {
                            $('#idarticulo').select2();
                        });
                    </script>
                    <div class="col-2">
                        <label for="floatingInput" class="mb-1"><strong>Precio</strong></label>
                        <input type="text" class="form-control form-control-sm" id="precio" autocomplete="off" onkeyup="format(this)"
                            onchange="format(this)">
                    </div>
                    <div class="col-2">
                        <label for="floatingInput" class="mb-1"><strong>Cantidad</strong></label>
                        <div class="input-group">
                            {{-- <div class="form-floating"> --}}
                            <input type="number" class="form-control form-control-sm" id="cantidad" value="1" autocomplete="off"
                                placeholder="cantidad" min="1" max="1000">
                            {{-- </div> --}}
                            <button type="button" class="btn btn-success" id='boton-guardar' role='button'><i
                                    class="fas fa-check"></i></button>
                        </div>
                    </div>
                </div>
                <table class="table table-striped table-sm" id="detalle">
                    <thead>
                        <tr class="table-secondary">
                            <th width="8%"><div align="center">ID Art.</div></th>
                            <th width="48%">Articulo</th>
                            <th width="12%">Precio</th>
                            <th width="12%">Cantidad</th>
                            <th width="12%">Subtotal</th>
                            <th width="8%">&nbsp;</th>
                        </tr>
                    </thead>
                    <tbody id="tbody"></tbody>
                </table>
                <div align="right">
                    <div class="col-2">
                        <div class="form-floating">
                            <input type="text" readonly value="0" class="form-control" id="total"
                                name="total">
                            <label for="floatingInput"><strong>Total</strong></label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-footer" align="right">
                <a href="{{ url('/compra') }}" class="btn btn-secondary">Cancelar</a>
                <input type="submit" value="Guardar" class="btn btn-success">
            </div>
        </div>
    </form>
@endsection
<style>
    #sinbordefondo {
        background: transparent;
        border: 0;
    }
    #subtotal {
        background: transparent;
        border: 0;
    }
</style>
@push('scripts')
    <script type="text/javascript">
        $(document).ready(function() {
            var contador = 1
            var detalle = new Array();
            $("#boton-guardar").click(function() {
                if (!$("#precio").val()) {
                    alert('Especifique el precio')
                } else {
                    if (!$("#cantidad").val()) {
                        alert('Especifique la cantidad')
                    } else {
                        var art = document.getElementById("idarticulo");
                        var artnombre = art.options[art.selectedIndex].text;
                        var cantidad = separadorMiles($("#cantidad").val());
                        /*--------------------------------------------------*/
                        var valortotal = $("#total").val();
                        var totalventa = valortotal.replace(/\./g, '')
                        var valorprecio = $("#precio").val();
                        var precio = valorprecio.replace(/\./g, '')
                        var cantidad = $("#cantidad").val();
                        var subtotal = parseFloat(precio) * parseFloat(cantidad);
                        var total = parseFloat(totalventa) + parseFloat(subtotal)
                        $('#total').val(separadorMiles(total))
                        var idarticulo = $("#idarticulo").val();
                        var precio = separadorMiles($("#precio").val());
                        $("#detalle").find('tbody')
                            .append($('<tr>')
                                .append($('<td>' +
                                    '<input type="text" class="form-control" id="sinbordefondo" readonly value="' +
                                    idarticulo + '" name="det[' + contador + '][idarticulo]"' + '</td>'
                                ))
                                .append($('<td>' +
                                    '<input type="text" class="form-control" id="sinbordefondo" readonly value="' +
                                    artnombre + '" name="det[' + contador + '][artnombre]"' + '</td>'))
                                .append($('<td>' +
                                    '<input type="text" class="form-control" id="sinbordefondo" readonly value="' +
                                    precio + '" name="det[' + contador + '][precio]"' + '</td>'))
                                .append($('<td>' +
                                    '<input type="text" class="form-control" id="sinbordefondo" readonly value="' +
                                    cantidad + '" name="det[' + contador + '][cantidad]"' + '</td>'))
                                .append($('<td>' +
                                    '<input type="text" class="form-control" id="subtotal" readonly value="' +
                                    separadorMiles(subtotal) + '" name="det[' + contador + '][subtotal]"' + '</td>'))
                                .append($(
                                    '<td width="5%"><div class="navbar"><a class="btn btn-danger btn-sm" id="borrar"><strong>-</strong></a></div></td>'
                                ))
                                .append($('</tr>'))
                            );


                        /* $("#detalle").find('tbody')
                            .append($('<tr>')
                                .append($('<td>' + artnombre + '</td>'))
                                .append($('<td>' + precio + '</td>'))
                                .append($('<td>' + cantidad + '</td>'))
                                .append($('<td>' + subtotal + '</td>'))
                                .append($('<td>' +
                                    '<a class="btn lnr lnr-pencil" onclick="eliminar(this)"></a>' -
                                    '</td>'))
                                .append($('</tr>'))
                            );


                        detalle.push({
                            artcodigo:$("#artco").val(), 
                            idarticulo: $("#idarticulo").val(),
                            precio: $("#precio").val(),
                            cantidad: $("#cantidad").val(),
                            subtotal: $("#cantidad").val() * $("#precio").val(),
                        }); */
                    }
                }
                contador++
                /* console.table(detalle);
                console.log(detalle) */
                /* $('#objet_detalle').val(JSON.stringify(detalle)); */
                $("#precio").val('');
                $("#cantidad").val('1');
            });
            $(document).on('click', '#borrar', function(event) {
                $(this).parents("tr").remove(); // se elimina el registro
                total = 0 //inicializacion de variable 
                $('#detalle tbody tr').each(function() { // se recorre la tabla hasta el registro
                    var valor = $(this).find('input[id="subtotal"]')
                        .val(); //se busca y se asigna el valor del subtotal
                    total = parseFloat(total) + parseFloat(valor); // se acumula subtotal
                });
                $('#total').val(total) //se asigna subtotal a total
            });
        });
    </script>
@endpush
