<script>
    $('body').on('click', '.btn-print', function()
    {
        let id = $(this).data('id');
        $.ajax({
            url: "<?php echo e(route('admin.print_reference_guide')); ?>",
            method: "POST",
            data: {
                '_token': "<?php echo e(csrf_token()); ?>",
                id: id
            },
            beforeSend: function() {
                block_content('#layout-content');
            },
            success: function(r) {
                if (!r.status) {
                    close_block('#layout-content');
                    toast_msg(r.msg, r.type);
                    return;
                }
                close_block('#layout-content');
                let pdf                 =   `<?php echo e(asset('files/reference-guides/${r.pdf}')); ?>`;
                var iframe              = document.createElement('iframe');
                iframe.style.display    = "none";
                iframe.src              = pdf;
                document.body.appendChild(iframe);
                iframe.contentWindow.focus();
                iframe.contentWindow.print();
            },
            dataType: "json"
        });
    });

    $('body').on('click', '.btn-view', function() {
        event.preventDefault();
        let id = $(this).data('id');
        $.ajax({
            url         : "<?php echo e(route('admin.view_detail_guide')); ?>",
            method      : "POST",
            data        : {
                '_token': "<?php echo e(csrf_token()); ?>",
                id      : id
            },
            beforeSend: function() {
                block_content('#layout-content');
            },
            success     : function(r){
                if (!r.status) {
                    close_block('#layout-content');
                    toast_msg(r.msg, r.type);
                    return;
                }
                close_block('#layout-content');
                console.log(r.data.reference_guide);
                let reference = r.data.reference_guide;
                $('.detail-document').html(reference.serie + '-' + reference.correlativo);
                $('.detail-code').html(reference.codigo);
                $('.detail-receipt').html(reference.fecha_emision);
                $('.detail-translate').html(reference.fecha_traslado);
                $('.detail-sender').html(reference.remitente);
                $('.detail-client').html(reference.destinatario);
                $('.detail-origin').html(reference.origen_provincia);
                $('.detail-destination').html(reference.destino_provincia);
                $('.detail-pay-mode').html(reference.modo_pago_guia);
                $('.detail-password').html(reference.password);
                $('#modalDetailGuide').offcanvas('show');
            },
            dataType    : "json"
        });
    });

    $('body').on('click', '.btn-detail', function() {
        event.preventDefault();
        let id = $(this).data('id');
        $.ajax({
            url         : "<?php echo e(route('admin.detail_guide')); ?>",
            method      : "POST",
            data        : {
                '_token': "<?php echo e(csrf_token()); ?>",
                id      : id
            },
            beforeSend: function() {
                block_content('#layout-content');
            },
            success     : function(r){
                if (!r.status) {
                    close_block('#layout-content');
                    toast_msg(r.msg, r.type);
                    return;
                }
                close_block('#layout-content');
                let reference = r.data.reference_guide;
                $('#modalUpdate select[name="idconductor"]').val(reference.idconductor).select2({
                    dropdownParent: $('#modalUpdate')
                });
                
                $('#modalUpdate input[name="id"]').val(reference.id);
                $(`#modalUpdate select[name="modo_pago"] option[value="${reference.idforma_pago}"]`).attr("selected", "selected");
                $(`#modalUpdate select[name="estado"] option[value="${reference.estado}"]`).attr("selected", "selected");
                $('#modalUpdate input[name="fecha_traslado"]').val(reference.fecha_traslado);
                $('#modalUpdate').modal('show');
            },
            dataType    : "json"
        });
    });

    // New driver
    function success_save_driver(msg = null, type = null, idtipocomprobante = null, last_id = null) {
        toast_msg(msg, type);
        load_drivers(idtipocomprobante);
        setTimeout(() => {
            $('#modalUpdate select[name="idconductor"]').val(last_id);
            $('#modalUpdate select[name="idconductor"]').trigger('change');
        }, 500);
    }

    function open_modal_driver(){
    }

    function load_drivers(idtipo_documento) {
        $.ajax({
            url: "<?php echo e(route('admin.get_up_drivers')); ?>",
            method: 'POST',
            data: {
                '_token': "<?php echo e(csrf_token()); ?>",
                idtipo_documento: idtipo_documento
            },
            success: function(r) {
                if (!r.status) {
                    toast_msg(r.msg, r.type);
                    return;
                }

                let html_drivers = '';
                $.each(r.drivers, function(index, driver) {
                    html_drivers +=
                        `<option value="${driver.id}">${driver.nombres}</option>`;
                });

                $('#modalUpdate #form_edit select[name="idconductor"]').html(html_drivers).select2({
                    dropdownParent: $('#modalUpdate')
                });
            },
            dataType: 'json'
        });
    }

    $('body').on('click', '#modalUpdate .btn-store', function() {
        event.preventDefault();
        let form = $('#modalUpdate #form_edit').serialize();
        $.ajax({
                url         :  "<?php echo e(route('admin.store_reference_guide')); ?>",
                method      : 'POST',
                data        : form,
                beforeSend  : function(){
                    $('#modalUpdate .btn-store').prop('disabled', true);
                    $('#modalUpdate .text-store').addClass('d-none');
                    $('#modalUpdate .text-storing').removeClass('d-none');
                },
                success     : function(r)
                {
                    if(!r.status)
                    {
                        $('#modalUpdate .btn-store').prop('disabled', false);
                        $('#modalUpdate .text-store').removeClass('d-none');
                        $('#modalUpdate .text-storing').addClass('d-none');
                        toast_msg(r.msg, r.type);
                        return;
                    }

                    $('#modalUpdate').modal('hide');
                    $('#modalUpdate .btn-store').prop('disabled', false);
                    $('#modalUpdate .text-store').removeClass('d-none');
                    $('#modalUpdate .text-storing').addClass('d-none');
                    toast_msg(r.msg, r.type);
                    reload_table();
                },
                dataType    : 'json'
            });
    });


    // Arreglar aquí
    $('body').on('click', '.btn-gen-voucher', function() {
        event.preventDefault();
        let id = $(this).data('id');
        $.ajax({
            url             : "<?php echo e(route('admin.view_detail_confirm')); ?>",
            method          : "POST",
            data            : {
                '_token'    : "<?php echo e(csrf_token()); ?>",
                id          : id
            },
            success         : function(r){
                if(!r.status){
                    toast_msg(r.msg, r.type);
                    return;
                }

                let tbody = '';
                $.each(r.detalle, function(index, detalle) {
                    tbody += `<tr>
                    <td>${index + 1}</td>
                    <td>${detalle.producto}</td>
                    <td>${parseFloat(detalle.precio_unitario).toFixed(2)}</td>
                    <td>${parseFloat((detalle.precio_unitario * detalle.cantidad)).toFixed(2)}</td>
                    </tr>`;
                });

                $('#modalConfirm #wrapper_tbody_resumen').html(tbody);
                $('#modalConfirm input[name="idguide"]').val(r.reference.id);
                $('#modalConfirm').modal('show');
            },
            dataType        : "json"
        });
    });

    $('body').on('click', '#modalConfirm .btn-confirm', function() {
        event.preventDefault();
        let id          = $('#modalConfirm input[name="idguide"]').val(),
            idpago      = $('#modalConfirm select[name="modo_pago"]').val();

            Swal.fire({
            title: "Confirmar contraseña",
            input: "password",
            inputPlaceholder: 'La contraseña debe tener 04 digitos',
            inputAttributes: {
                autocapitalize: "off",
                maxlength: 4
            },
            showDenyButton: false,
            showCancelButton: true,
            confirmButtonText: "Confirmar",
            cancelButtonText: "Cancelar",
            showLoaderOnConfirm: true,
            preConfirm: async (login) => {},
            allowOutsideClick: false
            }).then((result) => {
                if (result.isConfirmed) {
                    block_content('#layout-content');
                    let value = result.value;
                    $.ajax({
                        url             : "<?php echo e(route('admin.gen_voucher_guide')); ?>",
                        method          : 'POST',
                        data            : {
                            '_token'    : "<?php echo e(csrf_token()); ?>",
                            id          : id,
                            contrasena  : value,
                            idpago      : idpago
                        },
                        success         : function(r){
                            if(!r.status){
                                close_block('#layout-content');
                                toast_msg(r.msg, r.type);
                                open_swal(id, idpago);
                                return;
                            }
                            
                            send_data_sunat(r.id, r.pdf);
                        },
                        dataType        : "json"
                    });
                }
        });
    });

    async function open_swal(idguia, idpago) {
        await Swal.fire({
            title: "Confirmar contraseña",
            input: "password",
            inputPlaceholder: 'La contraseña debe tener 04 digitos',
            inputAttributes: {
                autocapitalize: "off",
                maxlength: 4
            },
            showDenyButton: false,
            showCancelButton: true,
            confirmButtonText: "Confirmar",
            cancelButtonText: "Cancelar",
            showLoaderOnConfirm: true,
            preConfirm: async (login) => {},
            allowOutsideClick: false
            }).then((result) => {
                if (result.isConfirmed) {
                    block_content('#layout-content');
                    let value = result.value;
                    $.ajax({
                        url             : "<?php echo e(route('admin.gen_voucher_guide')); ?>",
                        method          : 'POST',
                        data            : {
                            '_token'    : "<?php echo e(csrf_token()); ?>",
                            id          : idguia,
                            contrasena  : value,
                            idpago      : idpago
                        },
                        success         : function(r){
                            if(!r.status){
                                close_block('#layout-content');
                                toast_msg(r.msg, r.type);
                                open_swal(idguia);
                                return;
                            }
                            
                            send_data_sunat(r.id, r.pdf);
                        },
                        dataType        : "json"
                    });
                }
            });
    }

    function send_data_sunat(id, ticket)
    {
        $.ajax({
            url             : "<?php echo e(route('admin.send_bf')); ?>",
            method          : "POST",
            data            : {
                '_token'    : "<?php echo e(csrf_token()); ?>",
                id          : id
            },
            beforeSend      : function(){},
            success         : function(r){
                if(!r.status){}
               
                let ip          = r.empresa.url_api,
                    api         = "Api/index.php",
                    datosJSON   = JSON.stringify(r.data);
                    datosJSON   = unescape(encodeURIComponent(datosJSON)),
                    idfactura   = parseInt(r.idfactura);

                    $.ajax({    
                        url         : ip + api,
                        method      : 'POST',
                        data        : {datosJSON},
                        beforeSend  : function(){},
                    }).done(function(res){
                        close_block('#layout-content');
                        if (res.trim() == "No se registró") 
                        {
                            toast_msg('El número de comprobante electrónico esta duplicado, revise la base de datos', 'error');
                            return;
                        }

                        $('#modalConfirm').modal('hide');
                        let respuesta_sunat = JSON.parse(res),
                            estado_conexion = JSON.parse(respuesta_sunat).status;
                    
                        let pdf = `<?php echo e(asset('files/billings/ticket/${ticket}')); ?>`;
                        var iframe = document.createElement('iframe');
                        iframe.style.display = "none";
                        iframe.src = pdf;
                        document.body.appendChild(iframe);
                        iframe.contentWindow.focus();
                        iframe.contentWindow.print();
                        reload_table();
                        if(estado_conexion != false)
                        {
                            update_cdr(idfactura);
                        }
                    }).fail(function(jqxhr, textStatus, error){
                        $('#modalConfirm').modal('hide');
                        close_block('#layout-content');
                        let pdf = `<?php echo e(asset('files/billings/ticket/${ticket}')); ?>`;
                        var iframe = document.createElement('iframe');
                        iframe.style.display = "none";
                        iframe.src = pdf;
                        document.body.appendChild(iframe);
                        iframe.contentWindow.focus();
                        iframe.contentWindow.print();
                        reload_table();
                    });
            },
            dataType        : "json"
        });
    }

    function update_cdr(idfactura)
    {
        let resp = '';
        $.ajax({
            url     : "<?php echo e(route('admin.update_cdr_bf')); ?>",
            method  : 'POST',
            data    : {
                '_token'   : "<?php echo e(csrf_token()); ?>",
                idfactura  : idfactura
            },
            success : function(r){},
            dataType : 'json'
        });
    }

    // Sale Note
    $('body').on('click', '.btn-gen-sale-note', function() {
        event.preventDefault();
        let id = $(this).data('id');
        $.ajax({
            url             : "<?php echo e(route('admin.view_detail_confirm_sale_note')); ?>",
            method          : "POST",
            data            : {
                '_token'    : "<?php echo e(csrf_token()); ?>",
                id          : id
            },
            success         : function(r){
                if(!r.status){
                    toast_msg(r.msg, r.type);
                    return;
                }

                let tbody = '';
                $.each(r.detalle, function(index, detalle) {
                    tbody += `<tr>
                    <td>${index + 1}</td>
                    <td>${detalle.producto}</td>
                    <td>${parseFloat(detalle.precio_unitario).toFixed(2)}</td>
                    <td>${parseFloat((detalle.precio_unitario * detalle.cantidad)).toFixed(2)}</td>
                    </tr>`;
                });

                $('#modalConfirmSaleNote #wrapper_tbody_resumen').html(tbody);
                $('#modalConfirmSaleNote input[name="idguide"]').val(r.reference.id);
                $('#modalConfirmSaleNote').modal('show');
            },
            dataType        : "json"
        });
    });

    $('body').on('click', '#modalConfirmSaleNote .btn-confirm', function() {
        event.preventDefault();
        let id          = $('#modalConfirmSaleNote input[name="idguide"]').val(),
            idpago      = $('#modalConfirmSaleNote select[name="modo_pago"]').val();

            Swal.fire({
            title: "Confirmar contraseña",
            input: "password",
            inputPlaceholder: 'La contraseña debe tener 04 digitos',
            inputAttributes: {
                autocapitalize: "off",
                maxlength: 4
            },
            showDenyButton: false,
            showCancelButton: true,
            confirmButtonText: "Confirmar",
            cancelButtonText: "Cancelar",
            showLoaderOnConfirm: true,
            preConfirm: async (login) => {},
            allowOutsideClick: false
            }).then((result) => {
                if (result.isConfirmed) {
                    block_content('#layout-content');
                    let value = result.value;
                    $.ajax({
                        url             : "<?php echo e(route('admin.gen_voucher_sale_note')); ?>",
                        method          : 'POST',
                        data            : {
                            '_token'    : "<?php echo e(csrf_token()); ?>",
                            id          : id,
                            contrasena  : value,
                            idpago: idpago
                        },
                        success         : function(r){
                            if(!r.status){
                                close_block('#layout-content');
                                toast_msg(r.msg, r.type);
                                open_swal_sale_note(id, idpago);
                                return;
                            }
                            
                            close_block('#layout-content');
                            open_ticket_sn(r.pdf);
                        },
                        dataType        : "json"
                    });
                }
        });
    });

    async function open_swal_sale_note(idguia, idpago) {
        await Swal.fire({
            title: "Confirmar contraseña",
            input: "password",
            inputPlaceholder: 'La contraseña debe tener 04 digitos',
            inputAttributes: {
                autocapitalize: "off",
                maxlength: 4
            },
            showDenyButton: false,
            showCancelButton: true,
            confirmButtonText: "Confirmar",
            cancelButtonText: "Cancelar",
            showLoaderOnConfirm: true,
            preConfirm: async (login) => {},
            allowOutsideClick: false
            }).then((result) => {
                if (result.isConfirmed) {
                    block_content('#layout-content');
                    let value = result.value;
                    $.ajax({
                        url             : "<?php echo e(route('admin.gen_voucher_sale_note')); ?>",
                        method          : 'POST',
                        data            : {
                            '_token'    : "<?php echo e(csrf_token()); ?>",
                            id          : idguia,
                            contrasena  : value,
                            idpago: idpago
                        },
                        success         : function(r){
                            if(!r.status){
                                close_block('#layout-content');
                                toast_msg(r.msg, r.type);
                                open_swal_sale_note(idguia, idpago);
                                return;
                            }

                            close_block('#layout-content');
                            open_ticket_sn(r.pdf);
                        },
                        dataType        : "json"
                    });
                }
            });
    }

    function open_ticket_sn(ticket) {
        $('#modalConfirmSaleNote').modal('hide');
        let pdf = `<?php echo e(asset('files/sale-notes/ticket/${ticket}')); ?>`;
        var iframe = document.createElement('iframe');
        iframe.style.display = "none";
        iframe.src = pdf;
        document.body.appendChild(iframe);
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        reload_table();
    }
</script><?php /**PATH C:\xampp\htdocs\courier\resources\views/admin/reference_guides/js-store.blade.php ENDPATH**/ ?>