<?php $__env->startSection('styles'); ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <h1 class="page-title">
        Gestión de UITs
    </h1>
    <div class="portlet light bordered">
        <div class="portlet-title">
            <div class="caption">
                <span class="caption-subject bold uppercase"> Lista de UITs </span>
                <span class="caption-helper"></span>
            </div>
            <div class="actions" style="padding-bottom: 0">
                <a class="btn btn-primary Crear" onclick="Agregar()">
                    <i class="fa fa-plus"></i>
                    <span class="hidden-xs"> A&ntilde;adir </span>
                </a>
            </div>
        </div>
        <div class="portlet-body">
            <table id="dataTable" class="table table-hover nowrap dataTable dtr-inline">
                <thead>
                <tr>
                    <th>Año</th>
                    <th>Valor S/.</th>
                    <th>Base Legal</th>
                    <th>Opciones</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <div id="modalAgregar" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalAgregar">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title caption-subject font-blue-secondary sbold uppercase">Agregar UIT</h4>
                </div>
                <div class="modal-body">
                    <?php echo e(Form::open(array('id' => 'form-validation', 'class'=>'form-horizontal', 'name' => 'formAgregar', 'onsubmit' => 'AgregarResult(this, event)'))); ?>

                    <div class="form-body">
                        <div class="form-group">
                            <div class="col-xs-12">
                                <?php echo Form::label('anio', 'Año:', ['class' => 'control-label']); ?>

                                <?php echo Form::number('anio', Carbon\Carbon::now()->year, ['class' => 'form-control', 'required' => 'required', 'disabled' => false, 'readonly' => 'readonly', 'min' => '0', 'step' => '0.01']); ?>

                            </div>
                            <div class="col-xs-12">
                                <?php echo Form::label('valor', 'Valor:', ['class' => 'control-label']); ?>

                                <?php echo Form::number('valor', null, ['class' => 'form-control', 'required' => 'required', 'min' => '0', 'step' => '0.01']); ?>

                            </div>
                            <div class="col-xs-12">
                                <?php echo Form::label('base_legal', 'Base Legal:', ['class' => 'control-label']); ?>

                                <?php echo Form::textarea('base_legal', null, ['class' => 'form-control', 'required' => 'required', 'style' => 'resize: none']); ?>

                            </div>
                        </div>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-offset-0 col-xs-12">
                                    <a class="btn btn-default" href="#" data-dismiss="modal">Cancelar</a>
                                    <?php echo Form::submit('Guardar', ['class' => 'btn btn-primary', 'name' => 'submit']); ?>

                                </div>
                            </div>
                        </div>
                    </div>
                    <?php echo Form::close(); ?>

                </div>
            </div>
        </div>
    </div>
    <div id="modalEditar" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalEditar">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title caption-subject font-blue-secondary sbold uppercase">Editar UIT</h4>
                </div>
                <div class="modal-body">
                    <?php echo e(Form::open(array('id' => 'form-validation', 'class' => 'form-horizontal', 'name' => 'formEditar', 'onsubmit' => 'EditarResult(this, event)'))); ?>

                    <div class="form-body">
                        <?php echo Form::hidden('id', null, ['id' => 'editarId', 'class' => 'form-control']); ?>

                        <div class="form-group">
                            <div class="col-xs-12">
                                <?php echo Form::label('anio', 'Año:', ['class' => 'control-label']); ?>

                                <?php echo Form::number('anio', null, ['id' => 'editarAnio', 'class' => 'form-control', 'required' => 'required', 'disabled' => false, 'readonly' => 'readonly', 'min' => '0', 'step' => '0.01']); ?>

                            </div>
                            <div class="col-xs-12">
                                <?php echo Form::label('valor', 'Valor en Soles:', ['class' => 'control-label']); ?>

                                <?php echo Form::number('valor', null, ['id' => 'editarValor', 'class' => 'form-control', 'required' => 'required', 'min' => '0', 'step' => '0.01']); ?>

                            </div>
                            <div class="col-xs-12">
                                <?php echo Form::label('base_legal', 'Base Legal:', ['class' => 'control-label']); ?>

                                <?php echo Form::textarea('base_legal', null, ['id' => 'editarBaseLegal', 'class' => 'form-control', 'required' => 'required', 'style' => 'resize: none']); ?>

                            </div>
                        </div>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-offset-0 col-xs-12">
                                    <a class="btn btn-default" href="#" data-dismiss="modal">Cancelar</a>
                                    <?php echo Form::submit('Guardar', ['class' => 'btn btn-primary', 'name' => 'submit']); ?>

                                </div>
                            </div>
                        </div>
                    </div>
                    <?php echo Form::close(); ?>

                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    <script>
        var dataTableLanguage = {
            "sProcessing":     "Procesando...",
            "sLengthMenu":     "Mostrar _MENU_ registros",
            "sZeroRecords":    "No se encontraron resultados",
            "sEmptyTable":     "Ningún dato disponible en esta tabla",
            "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix":    "",
            "sSearch":         "Buscar:",
            "sUrl":            "",
            "sInfoThousands":  ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst":    "Primero",
                "sLast":     "Último",
                "sNext":     "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        };
        var dataTable = [
            function (args) {
                $("#dataTable").DataTable({
                    language: dataTableLanguage,
                    processing: true,
                    serverSide: true,
                    destroy: true,
                    responsive: true,
                    ajax: {
                        data: null,
                        type: "POST",
                        url: "<?php echo e(route('admin.uit.post')); ?>",
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*console.log(jqXHR);
                            console.log(textStatus);
                            console.log(errorThrown);*/
                        }
                    },
                    columns: [
                        {
                            data: "anio",
                            name: "anio"
                        },
                        {
                            data: "valor",
                            name: "valor"
                        },
                        {
                            data: "base_legal",
                            name: "base_legal"
                        },
                        {
                            data: "id",
                            name: "id",
                            render: function (data, type, row) {
                                var render = "";
                                render += "<td class=\"td_center\">";
                                render += " <a onclick=\"Editar(" + data + ", '" + row.anio + "', '" + row.valor + "', '" + row.base_legal + "')\" title=\"Editar\" class=\"btn btn-outline btn-circle btn-sm purple\">";
                                render += "     <i class=\"fa fa-edit\"></i> Editar";
                                render += " </a>";
                                render += " <a onclick=\"Eliminar(" + data + ")\" title=\"Eliminar\" class=\"btn btn-outline btn-circle dark btn-sm black\">";
                                render += "     <i class=\"fa fa-trash-o\"></i> Eliminar";
                                render += " </a>";
                                render += "</td>";

                                return render;
                            }
                        }
                    ],
                    order: [
                        [0, "desc"]
                    ]
                });
            }
        ];

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        function CargarDataTables(index, args) {
            index = index || -1;
            args = args || null;

            if (index < 0) {
                var dataTableLength = dataTable.length;
                for (var i = 0; i < dataTableLength; i++) {
                    dataTable[i](args);
                }
            } else {
                dataTable[index](args);
            }
        }

        function Agregar() {
            $("#modalAgregar").modal("show");
        }

        function AgregarResult(element, event) {
            event.preventDefault();

            var formName = element.name;
            var form = document.forms[formName];
            var data = {
                anio: form["anio"].value,
                valor: form["valor"].value,
                base_legal: form["base_legal"].value
            };

            $.ajax({
                data: data,
                type: "POST",
                url: "<?php echo e(route('admin.uit.agregar.post')); ?>",
                beforeSend: function (jqXHR, settings) {
                    /*console.log(jqXHR);
                    console.log(settings);*/

                    form["submit"].disabled = true;
                },
                complete: function (jqXHR, textStatus) {
                    /*console.log(jqXHR);
                    console.log(textStatus);*/

                    form["anio"].value = "";
                    form["valor"].value = "";
                    form["base_legal"].value = "";
                    form["submit"].disabled = false;

                    $("#modalAgregar").modal("hide");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    /*console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);*/
                     
                    swal({
                        showCancelButton: false,
                        showConfirmButton: true,
                        text: "No se pudo agregar el registro",
                        title: "Error",
                        type: "error"
                    }, function (isConfirm) {

                    });
                },
                success: function (data, jqXHR, settings) {
                    /*console.log(data);
                    console.log(jqXHR);
                    console.log(settings);*/

                    if (data) {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "El registro se agregó exitosamente",
                            title: "Éxito",
                            type: "success"
                        }, function (isConfirm) {

                        });

                        CargarDataTables();
                    } else {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "No se pudo agregar el registro",
                            title: "Error",
                            type: "error"
                        }, function (isConfirm) {

                        });
                    }
                }
            });

            return false;
        }

        function Editar(id, anio, valor, base_legal) {
            document.getElementById("editarId").value = id;
            document.getElementById("editarAnio").value = anio;
            document.getElementById("editarValor").value = valor;
            document.getElementById("editarBaseLegal").value = base_legal;

            $("#modalEditar").modal("show");
        }

        function EditarResult(element, event) {
            event.preventDefault();

            var formName = element.name;
            var form = document.forms[formName];
            var data = {
                id: form["id"].value,
                valor: form["valor"].value,
                base_legal: form["base_legal"].value
            };

            $.ajax({
                data: data,
                type: "POST",
                url: "<?php echo e(route('admin.uit.editar.post')); ?>",
                beforeSend: function (jqXHR, settings) {
                    /*console.log(jqXHR);
                    console.log(settings);*/

                    form["submit"].disabled = true;
                },
                complete: function (jqXHR, textStatus) {
                    /*console.log(jqXHR);
                    console.log(textStatus);*/

                    form["submit"].disabled = false;

                    $("#modalEditar").modal("hide");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    /*console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);*/
                    
                    swal({
                        showCancelButton: false,
                        showConfirmButton: true,
                        text: "No se pudo editar el registro",
                        title: "Error",
                        type: "error"
                    }, function (isConfirm) {

                    });
                },
                success: function (data, jqXHR, settings) {
                    /*console.log(data);
                    console.log(jqXHR);
                    console.log(settings);*/

                    if (data) {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "El registro se editó exitosamente",
                            title: "Éxito",
                            type: "success"
                        }, function (isConfirm) {

                        });

                        CargarDataTables();
                    } else {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "No se pudo editar el registro",
                            title: "Error",
                            type: "error"
                        }, function (isConfirm) {

                        });
                    }
                }
            });

            return false;
        }

        function Eliminar(id) {
            swal({
                cancelButtonColor: "#dd3333",
                cancelButtonText: "No",
                confirmButtonColor: "#3085d6",
                confirmButtonText: "Sí",
                showCancelButton: true,
                showConfirmButton: true,
                text: "Una vez borrada no se podrá recuperar",
                title: "¿Está seguro de querer eliminar este registro?",
                type: "warning"
            }, function (isConfirm) {
                if (isConfirm) {
                    EliminarResult(id);
                }
            });
        }

        function EliminarResult(id) {
            var data = {
                id: id
            };

            $.ajax({
                data: data,
                type: "POST",
                url: "<?php echo e(route('admin.uit.eliminar.post')); ?>",
                beforeSend: function (jqXHR, settings) {
                    /*console.log(jqXHR);
                    console.log(settings);*/
                },
                complete: function (jqXHR, textStatus) {
                    /*console.log(jqXHR);
                    console.log(textStatus);*/
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    /*console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);*/
                     
                    swal({
                        showCancelButton: false,
                        showConfirmButton: true,
                        text: "No se pudo eliminar el registro",
                        title: "Error",
                        type: "error"
                    }, function (isConfirm) {

                    });
                },
                success: function (data, jqXHR, settings) {
                    /*console.log(data);
                     console.log(jqXHR);
                     console.log(settings);*/

                    if (data) {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "El registro se eliminó exitosamente",
                            title: "Éxito",
                            type: "success"
                        }, function (isConfirm) {

                        });

                        CargarDataTables();
                    } else {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "No se pudo eliminar el registro",
                            title: "Error",
                            type: "error"
                        }, function (isConfirm) {

                        });
                    }
                }
            });
        }

        window.onload = function() {
            CargarDataTables();
        };
    </script>
<?php $__env->stopSection(); ?>


<?php echo $__env->make('template.layout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>