// ================================
// 🔥 MODAL
// ================================
function abrirModal(url, modal="#modalGlobal"){

    let $modal = $(modal);

    $modal.modal("show");

    $modal.find('.modal-title').text('Cargando...');
    $modal.find('.modal-body').html('<div class="text-center p-3"><i class="fa fa-spinner fa-spin"></i> Cargando...</div>');

    $.get(url,function(html){

        $modal.find('.modal-body').html(html);
        // 🔥 si el HTML trae título
        let title = $modal.find('[data-title]').first().data('title');
        if(title){
            $modal.find('.modal-title').text(title);
        }
    });

}

// ================================
// 🔥 LOAD GOOGLE MAPS (UNA VEZ)
// ================================
function loadMaps(callback){

    if(typeof google !== "undefined"){
        callback();
        return;
    }

    window._initMapGlobal = function(){
        callback();
    };

    let script = document.createElement("script");
    script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAx2DGHDdkaMqGOSWExvT2qjRFvKGADW_Y&libraries=places&callback=_initMapGlobal";
    script.async = true;

    document.body.appendChild(script);
}

// ================================
// 🔥 INIT FORM CLIENTE
// ================================
function initFormCliente(){

    // 🔹 chosen
    $('.chosen-select').chosen();
    $('.chosen-select-deselect').chosen({ allow_single_deselect: true });

    let $input = $("#direccion");
    let $box   = $("#resultados");

    let debounceTimer = null;

    // 🔹 MAPS
    loadMaps(function(){

        window.autocompleteService = new google.maps.places.AutocompleteService();
        window.placesService = new google.maps.places.PlacesService(document.createElement('div'));
        window.sessionToken = new google.maps.places.AutocompleteSessionToken();

    });

    $input.prop("disabled",true);

    // ============================
    // 🔥 EVENTOS
    // ============================

    $(document).off('change.global','#departamento')
    .on('change.global','#departamento',function(){

        let id = $(this).val();

        $.ajax({
            url: rutaapp+'pais/municipios.php',
            type:"post",
            dataType:'html',
            data:{ id:id }
        }).done(function(response){

            $('#ciudad').html(response).slideDown(400);

            $input.prop("disabled",true).val('');
            $("#latitud").val('');
            $("#longitud").val('');
            $box.hide();

        });

    });

    $(document).off('change.global','#ciudad')
    .on('change.global','#ciudad',function(){

        if($(this).val()){
            $input.prop("disabled",false).focus();
        }else{
            $input.prop("disabled",true);
        }

        $("#latitud").val('');
        $("#longitud").val('');
    });

    $(document).off('input.global','#direccion')
    .on('input.global','#direccion',function(){

        let q = $(this).val().trim();
        let ciudad = $("#ciudad option:selected").text();

        if(q.length < 3){
            $box.hide();
            return;
        }

        clearTimeout(debounceTimer);

        debounceTimer = setTimeout(()=>{

            let query = q + ", " + ciudad + ", Colombia";

            autocompleteService.getPlacePredictions({
                input: query,
                sessionToken: sessionToken,
                componentRestrictions:{ country:"co" },
                types:["address"]
            },function(predictions,status){

                if(status !== google.maps.places.PlacesServiceStatus.OK || !predictions){
                    $box.hide();
                    return;
                }

                $box.html("");

                predictions.forEach(pred=>{

                    let $item = $('<a href="#" class="list-group-item list-group-item-action"></a>');
                    $item.text(pred.description);

                    $item.on("click",function(e){

                        e.preventDefault();

                        placesService.getDetails({
                            placeId: pred.place_id,
                            fields:["geometry","formatted_address"],
                            sessionToken: sessionToken
                        },function(place,status){

                            if(status !== google.maps.places.PlacesServiceStatus.OK){
                                swal("Error","No se pudo obtener ubicación","error");
                                return;
                            }

                            $("#direccion").val(place.formatted_address);
                            $("#latitud").val(place.geometry.location.lat());
                            $("#longitud").val(place.geometry.location.lng());

                            $box.hide();

                            sessionToken = new google.maps.places.AutocompleteSessionToken();
                        });

                    });

                    $box.append($item);
                });

                $box.show();

            });

        },300);

    });

    // cerrar lista
    $(document).off('click.global')
    .on('click.global',function(e){

        if(!$(e.target).closest("#direccion, #resultados").length){
            $box.hide();
        }

    });

}

// ================================
// 🔥 FORM AJAX (MODALES)
// ================================
$(document).off('submit.global','.form-ajax')
.on('submit.global','.form-ajax',function(e){

    e.preventDefault();

    let f = this;
    let btn = $(f).find('[type=submit]');

    btn.prop('disabled',true);

    swal({
        title:"Procesando",
        text:"Espere...",
        type:"info",
        showConfirmButton:false
    });

    $.ajax({
        url:f.action,
        type:f.method || 'POST',
        data:new FormData(f),
        processData:false,
        contentType:false,
        success:function(res){

            let r;

            try{
                r = JSON.parse(res);
            }catch(e){
                swal("Error","Respuesta inválida","error");
                btn.prop('disabled',false);
                return;
            }

            ejecutarAcciones(r);

            btn.prop('disabled',false);

        },
        error:function(){
            swal("Error","Fallo en la petición","error");
            btn.prop('disabled',false);
        }
    });

});

// ================================
// 🔥 ACCIONES JSON
// ================================
function ejecutarAcciones(r){

    if(r.swal){
        swal(r.swal.title,r.swal.text,r.swal.type);
    }else{
        swal.close();
    }

    if(r.select){
        let s=document.getElementById(r.select.id);
        if(s){
            s.add(new Option(r.select.text,r.select.value,true,true));
            $(s).trigger("chosen:updated");
        }
    }

    if(r.modal){
        $(r.modal).modal("hide");
    }

    if(r.redirect){
        setTimeout(()=>{
            location.href=r.redirect;
        },1500);
    }

}