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

<?php $__env->startSection('content'); ?>
    <h1 class="page-title">
        <a href="<?php echo e(url('admin/tramite')); ?>"><i class="icon-action-undo"></i></a>
        Agregar Trámite TUPA
    </h1>
    <div class="portlet light bordered">
        <div class="portlet-title">
            <div class="caption">
                <h1 class="caption-subject font-green sbold uppercase">Información General</h1>
            </div>
        </div>
        <div class="portlet-body">
            <div class="row">
                <div class="col-lg-12">
                    <?php echo e(Form::open(array('id' => 'form-validation', 'enctype' => 'multipart/form-data', 'name' => 'formAgregar', 'onsubmit' => 'AgregarResult(this, event)'))); ?>

                    <div class="form-horizontal">
                        <div class="form-group col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('nombre', '* Nombre:', ['class' => 'control-label']); ?>

                            <?php echo Form::text('nombre', null, ['class' => 'form-control', 'required' => 'required']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('id_tramite_categoria', 'Categoría:', ['class' => 'control-label']); ?>

                            <?php echo Form::select('id_tramite_categoria', array(null => '---'), null, ['id' => 'selectCategoria', 'class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('id_tramite_calificacion', 'Calificación:', ['class' => 'control-label']); ?>

                            <?php echo Form::select('id_tramite_calificacion', array(null => '---'), null, ['id' => 'selectCalificacion', 'class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('codigo', 'Código:', ['class' => 'control-label']); ?>

                            <?php echo Form::text('codigo', null, ['class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('cuenta_contable', 'Cuenta Contable:', ['class' => 'control-label']); ?>

                            <?php echo Form::text('cuenta_contable', null, ['class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('plazo_resolucion', '* Duración del Trámite (días):', ['class' => 'control-label']); ?>

                            <?php echo Form::number('plazo_resolucion', null, ['class' => 'form-control', 'min' => '0', 'pattern' => '\d+', 'required' => 'required']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('id_tramite_estado', 'Estado:', ['class' => 'control-label']); ?>

                            <?php echo Form::select('id_tramite_estado', array(null => '---'), null, ['id' => 'selectEstado', 'class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('id_area_inicio', 'Área Inicial:', ['class' => 'control-label']); ?>

                            <?php echo Form::select('id_area_inicio', array(null => '---'), null, ['id' => 'selectAreaInicio', 'class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('id_autoridad_competente', 'Autoridad Competente:', ['class' => 'control-label']); ?>

                            <?php echo Form::select('id_autoridad_competente', array(null => '---'), null, ['id' => 'selectAutoridadCompetente', 'class' => 'form-control']); ?>

                        </div>
                        <div class="form-group col-lg-12 col-xs-12" style="margin-right: 10px;">
                            <?php echo Form::label('base_legal', 'Base Legal:', ['class' => 'control-label']); ?>

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

                        </div>
                        <div class="form-actions" style="text-align: left; padding-top: 50px;">
                            <a class="btn dark btn-outline" href="<?php echo e(url('admin/tramite')); ?>">Cancelar</a>
                            <?php echo Form::submit('Guardar', ['class' => 'btn green btn-submit', 'name' => 'submit']); ?>

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

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

<?php $__env->startSection('scripts'); ?>
    <script>
        var tramiteCalificacion = JSON.parse('<?php echo json_encode(config('constants.TRAMITE_CALIFICACION')); ?>');
        var tramiteEstado = JSON.parse('<?php echo json_encode(config('constants.TRAMITE_ESTADO_NOMBRE')); ?>');

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

        function loadSelectOptions(elementId, data, selectedValue, nullable, value, name) {
            selectedValue = selectedValue || null;
            value = value || "id";
            name = name || "name";
            nullable = nullable || false;

            var selectOptions = "";
            var dataLength = data.length;

            if (nullable) {
                selectOptions += "<option value";

                if (selectedValue != null) {
                    selectOptions += " selected=\"selected\"";
                }

                selectOptions += ">---</option>";
            }

            for (var i = 0; i < dataLength; i++) {
                var dataRow = data[i];
                selectOptions += "<option value=\"";
                selectOptions += dataRow[value];
                selectOptions += "\"";

                if (dataRow[value] == selectedValue) {
                    selectOptions += " selected=\"selected\"";
                }

                selectOptions += ">";
                selectOptions += dataRow[name];
                selectOptions += "</option>";
            }

            document.getElementById(elementId).innerHTML = selectOptions;
        }

        function loadSelectOptions2(elementId, data, selectedValue, nullable) {
            selectedValue = selectedValue || null;
            nullable = nullable || false;

            var selectOptions = "";

            if (nullable) {
                selectOptions += "<option value";

                if (selectedValue != null) {
                    selectOptions += " selected=\"selected\"";
                }

                selectOptions += ">---</option>";
            }

            for (var key in data) {
                var value = data[key];
                selectOptions += "<option value=\"";
                selectOptions += key;
                selectOptions += "\"";

                if (key == selectedValue) {
                    selectOptions += " selected=\"selected\"";
                }

                selectOptions += ">";
                selectOptions += value;
                selectOptions += "</option>";
            }

            document.getElementById(elementId).innerHTML = selectOptions;
        }

        function CargarSelects() {
            loadSelectOptions2("selectCalificacion", tramiteCalificacion, null, false);
            loadSelectOptions2("selectEstado", tramiteEstado, null, false);

            $.ajax({
                data: null,
                type: "POST",
                url: "<?php echo e(route('admin.tramite.categoria.post')); ?>",
                error: function(jqXHR, textStatus, errorThrown) {
                    /*console.log(data);
                    console.log(jqXHR);
                    console.log(settings);*/
                },
                success: function(data, textStatus, jqXHR) {
                    /*console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);*/

                    loadSelectOptions("selectCategoria", data.data, null, true, "id", "nombre");
                }
            });

            $.ajax({
                data: null,
                type: "POST",
                url: "<?php echo e(route('admin.dependencia.post')); ?>",
                error: function(jqXHR, textStatus, errorThrown) {
                    /*console.log(data);
                    console.log(jqXHR);
                    console.log(settings);*/
                },
                success: function(data, textStatus, jqXHR) {
                    /*console.log(data);
                    console.log(jqXHR);
                    console.log(settings);*/

                    loadSelectOptions("selectAutoridadCompetente", data.data, null, true, "id", "nombre");
                    loadSelectOptions("selectAreaInicio", data.data, null, true, "id", "nombre");
                }
            });
        }

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

            var formName = element.name;
            var form = document.forms[formName];
            var data = {
                codigo: form["codigo"].value,
                cuenta_contable: form["cuenta_contable"].value,
                nombre: form["nombre"].value,
                base_legal: form["base_legal"].value,
                plazo_resolucion: form["plazo_resolucion"].value,
                id_area_inicio: form["id_area_inicio"].value,
                id_autoridad_competente: form["id_autoridad_competente"].value,
                id_tramite_calificacion: form["id_tramite_calificacion"].value,
                id_tramite_categoria: form["id_tramite_categoria"].value,
                id_tramite_estado: form["id_tramite_estado"].value
            };

            $.ajax({
                data: data,
                type: "POST",
                url: "<?php echo e(route('admin.tramite.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["submit"].disabled = false;
                },
                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) {

                        });

                        window.location.href = "<?php echo e(url('admin/tramite/editar/')); ?>" + "/" + data.id;
                    } else {
                        swal({
                            showCancelButton: false,
                            showConfirmButton: true,
                            text: "No se pudo agregar el registro",
                            title: "Error",
                            type: "error"
                        }, function (isConfirm) {

                        });
                    }
                }
            });

            return false;
        }

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


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