@extends('template.layout')

@section('styles')
@endsection

@section('content')
    <h1 class="page-title">
        <a href="{{ url('admin/tramite/editar/' . $tramiteProcedimiento->id) }}"><i class="icon-action-undo"></i></a>
        Agregar Resolución del Trámite TUPA
    </h1>
    <div class="portlet light bordered">
        <div class="portlet-body">
            <div class="row">
                <div class="col-lg-12">
                    {{ Form::open(array('id' => 'form-validation', 'enctype' => 'multipart/form-data', 'name' => 'formAgregar', 'onsubmit' => 'AgregarResult(this, event)')) }}
                    <div class="form-horizontal">
                        {!! Form::hidden('id_tramite_procedimiento', $tramiteProcedimiento->id, ['class' => 'form-control']) !!}
                        <div class="form-group col-xs-12" style="margin-right: 10px;">
                            {!! Form::label('tramite_procedimiento_nombre', 'Procedimiento:', ['class' => 'control-label']) !!}
                            {!! Form::text('tramite_procedimiento_nombre', $tramiteProcedimiento->nombre, ['class' => 'form-control', 'disabled' => false, 'readonly' => 'readonly']) !!}
                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            {!! Form::label('id_tramite_resolucion_tipo', '* Tipo de Resolución:', ['class' => 'control-label']) !!}
                            {!! Form::select('id_tramite_resolucion_tipo', array(null => '---'), null, ['id' => 'selectResolucionTipo', 'class' => 'form-control', 'required' => 'required']) !!}
                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            {!! Form::label('id_autoridad', 'Autoridad:', ['class' => 'control-label']) !!}
                            {!! Form::select('id_autoridad', array(null => '---'), null, ['id' => 'selectAutoridad', 'class' => 'form-control']) !!}
                        </div>
                        <div class="form-group col-lg-6 col-sm-6 col-xs-12" style="margin-right: 10px;">
                            {!! Form::label('plazo_presentacion', '* Plazo Presentación:', ['class' => 'control-label']) !!}
                            {!! Form::number('plazo_presentacion', 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;">
                            {!! Form::label('plazo_resolucion', '* Plazo Resolución:', ['class' => 'control-label']) !!}
                            {!! Form::number('plazo_resolucion', null, ['class' => 'form-control', 'min' => '0', 'pattern' => '\d+', 'required' => 'required']) !!}
                        </div>
                        <div class="form-actions" style="text-align: left; padding-top: 50px;">
                            <a class="btn dark btn-outline" href="{{ url('admin/tramite/editar/' . $tramiteProcedimiento->id) }}">Cancelar</a>
                            {!! Form::submit('Guardar', ['class' => 'btn green btn-submit', 'name' => 'submit']) !!}
                        </div>
                    </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        var tramiteResolucionTipo = JSON.parse('{!! json_encode(config('constants.TRAMITE_RESOLUCION_TIPO')) !!}');

        $.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("selectResolucionTipo", tramiteResolucionTipo, null, false);

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

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

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

            var formName = element.name;
            var form = document.forms[formName];
            var data = {
                plazo_presentacion: form["plazo_presentacion"].value,
                plazo_resolucion: form["plazo_resolucion"].value,
                id_autoridad: form["id_autoridad"].value,
                id_tramite_procedimiento: form["id_tramite_procedimiento"].value,
                id_tramite_resolucion_tipo: form["id_tramite_resolucion_tipo"].value
            };

            $.ajax({
                data: data,
                type: "POST",
                url: "{{ route('admin.tramite.resolucion.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 = "{{ url("admin/tramite/editar/") }}" + "/" + data.id_tramite_procedimiento;
                    } 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>
@endsection
