@extends('layout.main')
@section('contenido')
    <form action="{{ url('/venta') }}" 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>Venta restringida! </strong>{{Session::get('no_det')}}
            </div>
        @endif
        <div class="card ">
            <div class="card-header">
                <h4 class="card-title">Registrar Venta</h4>
            </div>
            <div class="card-body">
                <input type="hidden" value="{{$operacion['0']->operacion_nro}}" name="operacion_nro">
                <input type="hidden" value="{{$operacion['0']->idcaja}}" name="idcaja">
                <div class="row">
                    <div class="col-2 ">
                        {{-- <div class="form-floating"> --}}
                        {{-- @foreach ($date as $value)
                            <input type="text" value="{{$value->fecha}}">    
                        @endforeach --}}
                        {{-- @dd($date['0']->fecha) --}}
                        <label for="floatingInput" class="mb-1"><strong>Fecha</strong></label>
                        <input type="date" class="form-control" value="{{$date['0']->fecha}}" name="fecha" id="fecha" autocomplete="off"
                            placeholder="fecha">
                        {{-- </div> --}}
                    </div>
                    <div class="col-2">
                        {{-- <div class="form-floating"> --}}
                            <label for="floatingInput" class="mb-1"><strong>Condición</strong></label>
                            <select name="condicion" id="condicion" class="form-control">
                                <option value="CONTADO">CONTADO</option>
                                <option value="CREDITO">CREDITO</option>
                            </select>
                        {{-- </div> --}}
                    </div>
                    <div class="col-2">
                        {{-- <div class="form-floating"> --}}
                            <label for="floatingInput" class="mb-1"><strong>Factura N°</strong></label>
                            <input type="text" readonly class="form-control" name="fact_nro" id="fact_nro" autocomplete="off" value="{{$fact_nro}}">
                        {{-- </div> --}}
                    </div>
                    <div class="col-4">
                        {{-- <div class="form-floating"> --}}
                            <label for="floatingInput" class="mb-1"><strong>Cliente</strong></label>
                            <select name="idcliente" id="idcliente" class=" form-control js-example-basic-single">
                                @foreach ($clientes as $cliente)
                                    <option value="{{ $cliente['idcliente'] }}">{{ $cliente['denominacion'] }}</option>
                                @endforeach
                            </select>
                        {{-- </div> --}}
                    </div>
                </div>
            </div>
        </div>
        {{-- ARRAY --}}
        {{-- <input type="hidden" name="objet_detalle" id="objet_detalle"> --}}
        {{--  --}}
        <div class="card mb-2">
            <div class="card-header">
                <h4 class="card-title">Detalle</h4>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-3">
                        {{-- <div class="form-floating"> --}}
                            <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>
                    <div class="col-3">
                        {{-- <div class="form-floating"> --}}
                            <label for="floatingInput" class="mb-1"><strong>Artículo</strong></label>
                            <select id="idarticulo" class="form-control js-example-basic-single">
                                @foreach ($articulos as $articulo)
                                    <option value="{{ $articulo['idarticulo'] }}">{{ $articulo['nombre'] }}</option>
                                @endforeach
                            </select>
                        {{-- </div> --}}
                    </div>
                    <div class="col-2">
                        {{-- <div class="form-floating"> --}}
                            <label for="floatingInput" class="mb-1"><strong>Precio</strong></label>
                            <input type="text" class="form-control" id="precio" autocomplete="off"
                            onkeyup="format(this)" onchange="format(this)">
                        {{-- </div> --}}
                    </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" 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 class="col-1"> 
                        <button type="button" class="btn btn-primary" id='boton-guardar' role='button'><strong>+</strong></button>
                    </div> --}}
                </div>
                <table class="table table-striped table-sm" id="detalle">
                    <thead>
                        <tr class="table-secondary">
                            <th width="7%">ID Art.</th>
                            <th width="29%">Articulo</th>
                            <th width="29%">Depósito</th>
                            <th width="10%">Precio</th>
                            <th width="10%">Cantidad</th>
                            <th width="10%">Subtotal</th>
                            <th width="5%">&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('/venta') }}" class="btn btn-secondary">Cancelar</a>
                <input type="submit" value="Guardar" class="btn btn-success">
            </div>
        </div>
    </form>
    <script>
        $(document).ready(function() {
            $('.js-example-basic-single').select2();
        });
    </script>
@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('precio')
                } else {
                    if (!$("#cantidad").val()) {
                        alert('cantidad')
                    } else {
                        var art = document.getElementById("idarticulo");
                        var artnombre = art.options[art.selectedIndex].text;
                        var idarticulo = $("#idarticulo").val();
                        var dep = document.getElementById("iddeposito");
                        var deposito = dep.options[dep.selectedIndex].text;
                        var iddeposito = $("#iddeposito").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 precio = separadorMiles($("#precio").val());
                        var cantidad = separadorMiles($("#cantidad").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($('<input type="hidden" value="'+iddeposito+'" name="det[' + contador +'][iddeposito]">'))
                                .append($('<td>'+'<input type="text" class="form-control" id="sinbordefondo" readonly value="'+deposito+'" name="det[' + contador +'][deposito]"'+'</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>'))
                        );
                    }
                }
                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