@include('header')
@include('navigator_menu_principal')
<script type="text/javascript" src="{{ URL::asset('js/fancy/fancy.min.js') }}?v={{time()}}"> </script>


<div class="row" style="margin:20px;">
	<div class="col-md-6"><h3>Contrapartes con prepago</h3></div>
    <div class='col-md-6 text-right'>
    	<button type="Button" class="btn btn-primary btn-fidelitas mailing" style="width:130px;" data-toggle="modal" data-target="#modalPrepagos"><i class="fa fa-envelope"></i> Mail</button>
    	<button type="Button" class="btn btn-primary btn-fidelitas excel" style="width:130px;"><i class="fa fa-file-excel-o"></i> Exportar Excel</button>
    </div>
</div>

<div class="row" style="margin:20px;">
	<div class="col-md-12">
		<div id="loading" class="row" style="display:block;">
			<div class="col-md-1 col-md-offset-5"><img src="/images/loading.gif" class="img img-responsive" /></div>
		</div>
		<div id="contenido" style="display:none;"></div>
	</div>
</div>

<form action="/led/led-prepagos-data" method="post" id="frmPrepagos">
    {{csrf_field()}}
    <input type="hidden" name="contraparte" value="" id="_contraparte">
    <input type="hidden" name="transact_id" value="" id="_transact_id">
</form>

<form action="/led/led-prepagos-excel" method="post" id="frmExcel">
    {{csrf_field()}}
</form>

<form action="/led/led-prepagos-mailing" method="post" id="frmMailing">
    {{csrf_field()}}
	<input type="Hidden" name="contraparte" value="">
</form>


<div id="modalPrepagos" class="modal fade">
    <div class="modal-dialog" style="width:850px" id="modal-prepagos">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h3 class="modal-title" id="prepagos_title"></h3>
            </div>
            <div class="modal-body" id="prepagos_body"></div>
        </div>
    </div>
</div>



<script>

    $(document).ready(function() {

		var grid;

		var columns = [{ type : 'select', index : 'contraparte' },
						{ type : 'string' , title : 'Cliente' , index : 'nombre_cliente' ,   width : 270,  cellAlign : 'left', sortable : true , resizable : true , filter : {header:true} , align : 'center',flex:1 },
						{ type : 'string' , title : 'Contraparte' , index : 'nombre_persona' ,  width : 270, cellAlign : 'left', sortable : true , resizable : true , filter : {header:true} , align : 'center',flex:1 },
						{ type : 'string' , title : 'País' , index : 'country_name' , width : 110 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center' },
						{ type : 'string' , title : 'ID' , index : 'identificacion' , width : 110 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center'},
						{ type : 'string' , title : 'Plataforma' , index : 'plataforma_pago' , width : 100 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center', },
						{ 
						   type : 'string' , title : 'Ingresado' , 
						   index : 'fecha_creacion_dmy' , width : 120 , cellAlign : 'center', 
						   sortable : true , resizable : true ,  align : 'center',
						   sorter : function (dir, a, b) {
											if ($.trim(a) !== '')
											{
												a = a.substr(6,4) + a.substr(3,2) + a.substr(0,2); 
											}
											if ($.trim(b) !== '')
											{
												b = b.substr(6,4) + b.substr(3,2) + b.substr(0,2); 
											}
											switch (dir) {
												case 'asc':
													if ($.trim(a) === '') {
														a = '>'.repeat(10);
													}
													if ($.trim(b) === '') {
														b = '>'.repeat(10);
													}
													return (a > b) ? 1 : -1;
												case 'desc':
													return (b > a) ? 1 : -1;
											}
											return;
										}

						},
						{ type : 'string' , title : 'Monto' , index : 'valor' , width : 100 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center', },
						{ type : 'string' , title : 'Moneda' , index : 'moneda' , width : 75 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center' },
						{ type : 'string' , title : 'Status' , index : 'status' , width : 100 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:true} , align : 'center', },
						{ /*format: { read: 'Y-m-d', write: 'd/m/Y' }, type : 'date' , */
						   type : 'string' , 
						   title : 'Transacción' , index : 'fecha_transaccion_dmy' , width : 120 , cellAlign : 'center', 
						   sortable : true , resizable : true , filter : {header:false} , align : 'center', 
						   index : 'fecha_transaccion_dmy' , width : 120 , cellAlign : 'center', 
						   sortable : true , resizable : true ,  align : 'center',
						   sorter : function (dir, a, b) {
											if ($.trim(a) !== '')
											{
												a = a.substr(6,4) + a.substr(3,2) + a.substr(0,2); 
											}
											if ($.trim(b) !== '')
											{
												b = b.substr(6,4) + b.substr(3,2) + b.substr(0,2); 
											}
											switch (dir) {
												case 'asc':
													if ($.trim(a) === '') {
														a = '>'.repeat(10);
													}
													if ($.trim(b) === '') {
														b = '>'.repeat(10);
													}
													return (a > b) ? 1 : -1;
												case 'desc':
													return (b > a) ? 1 : -1;
											}
											return;
										}

						},
						{ type : 'string' , title : 'Cód. Transacc.' , index : 'preference_id' , width : 120 , cellAlign : 'center', sortable : true , resizable : false , filter : {header:false} , align : 'center'},
						{ type : 'string' , title : 'Facturado' , index : 'facturado' , width : 120 , cellAlign : 'center', sortable : true , resizable : true , filter : {header:false} , align : 'center', },
						{ /*format: { read: 'Y-m-d', write: 'd/m/Y' }, type : 'date' , */
						  type : 'string' , 
						  title : 'Fecha Factura' , index : 'fecha_facturado_dmy', width : 120, 
						  cellAlign : 'center', sortable : true , 
						  resizable : true ,  align : 'center', 
						  sorter : function (dir, a, b) {
											if ($.trim(a) !== '')
											{
												a = a.substr(6,4) + a.substr(3,2) + a.substr(0,2); 
											}
											if ($.trim(b) !== '')
											{
												b = b.substr(6,4) + b.substr(3,2) + b.substr(0,2); 
											}
											switch (dir) {
												case 'asc':
													if ($.trim(a) === '') {
														a = '>'.repeat(10);
													}
													if ($.trim(b) === '') {
														b = '>'.repeat(10);
													}
													return (a > b) ? 1 : -1;
												case 'desc':
													return (b > a) ? 1 : -1;
											}
											return;
										}
						},
						/*{ type : 'string' , title : 'Confirmación' , index : 'fecha_confirmacion' , width : 120 , cellAlign : 'center', sortable : true , resizable : false , filter : {header:false} , align : 'center'},*/
						{ type : 'string' , title : 'Acción' , index : 'acciones' , width : 90 , cellAlign : 'center', sortable : true , resizable : false , filter : {header:false} , align : 'center'},	
						];


        $.ajax({
                    method : 'post',
                    url : '/led/led-prepagos-data',
                    data : $('#frmPrepagos').serialize(),
                    dataType : 'json',
                    beforeSend : function() {
                        $('#loading').show();
                        $('#contenido').hide();
                    },
                    success : function(data) {
                        var contr = data.data;
                        var paises = data.paises;                     

                        grid = new FancyGrid({
													renderTo : 'contenido',
													height: 700,
													cellHeight: 42,
													theme: {
														name: 'blue',
													},
													lang: {
														paging: {
															info: 'Registros [0] - [1] de [2]',
															page: 'Página',
															of: 'de [0]'
														},
													},
													selModel: { type : 'rows', memory : true },
													paging : true,
													paging : {
														pageSize: 20,
														pageSizeData: [20],
														barType: 'tbar'
													},
													data: contr,
													columns: columns,
													events : [{cellclick : function(grid, obj) {
																						selection = grid.getSelection();
																					}
													}]
						});

                        $('#loading').hide();
                        $('#contenido').show();



                    }

        });

		$(document).on('click', '.excel', function () {
			$('#frmExcel').submit();
		});


		///////////////////

		$(document).on('click', '.mailing', function() {
			var s = grid.getSelection();
			$('#prepagos_title').html('Mailing');
			if( s.length > 0 ) {
				var c = '';
				$.each(s, function(i, el) {
					if (c != '') {
						c = c + ','
					}
					c = c + el.contraparte;
				});
				$('#frmMailing [name="contraparte"]').val(c);
				$.ajax({
							method : 'post',
							url : '/led/led-prepagos-mailing-form',
							data : $('#frmMailing').serialize(),
							beforeSend : function() {
								$('#prepagos_body').html('');
							},
							success : function(response) {
								$('#prepagos_body').html(response);
							}
				});
			}
			else {
				$('#prepagos_body').html('<br /><br /><h4 class="text-center">No se han seleccionado contrapartes</h4><br /><br /><br />');
			}

		});


		$(document).on('submit', '#frmMailingOptions', function(evt) {
			evt.preventDefault();
			$.ajax({
						method : 'post',
						url : '/led/led-prepagos-mailing-enviar',
						data : $(this).serialize(),
						dataType : 'json',
						beforeSend : function() {
							$('button').prop('disabled', true);
							$('#message_mailing').hide();
							$('#loading_mailing').show();
						},
						success : function(response) {
							$('#loading_mailing').hide();							
							$('#message_mailing_content').html(response.message);
							$('#message_mailing').show();
							setTimeout(function() {
								$('#message_mailing').hide();
								$('button').prop('disabled', false);
							}, 2500);
						}
			});
		});

		/////////////////

        $(document).on('click', '.mailpago', function() {
            $('#frmPrepagos [name="contraparte"]').val($(this).data('contraparte'));
            $('#frmPrepagos [name="transact_id"]').val($(this).data('transactId'));
            $.ajax({
                        method : 'post',
                        url : '/led/led-prepagos-enviar-link',
                        data : $('#frmPrepagos').serialize(),
                        beforeSend : function() {
                            $('#prepagos_title').html('Enviar e-mail de pago');
                            $('#prepagos_body').html('');
                        },
                        success : function(data) {
                            $('#prepagos_body').html(data);
                        }

            });
        });

        $(document).on('click', '.detalle', function() {
            $('#frmPrepagos [name="contraparte"]').val($(this).data('contraparte'));
            $('#frmPrepagos [name="transact_id"]').val($(this).data('transactId'));
            $.ajax({
                        method : 'post',
                        url : '/led/led-prepagos-detalle',
                        data : $('#frmPrepagos').serialize(),
                        beforeSend : function() {
                            $('#prepagos_title').html('Detalles');
                            $('#prepagos_body').html('');
                        },
                        success : function(data) {
                            $('#prepagos_body').html(data);
                        }

            });
        });


        //

		$(document).on('submit', '#frmPrepagosLink', function(e) {
			e.preventDefault();
			var go_ = true;
			if($('.enviar').is(':checked')) {
				if ($('#email').val() == '') {
					go_ = false;
					alert('Indique una dirección de e-mail para enviar el link de prepago.');
				}
			}
			if(go_) {

				$.ajax({
							method : 'post',
							url : '/led/led-prepagos-envio-link',
							data : $(this).serialize(),
							async : true,
							beforeSend : function() {
								$('#btn1, #btn2').prop('disabled', true);
								$('#loading_msg').removeClass('hidden');
							},
							success : function(data) {
								$('#loading_msg').addClass('hidden');
								
								var msg = JSON.parse(data);
								$('#mensaje').html(msg.mensaje);
								$('#mensaje').removeClass('hidden');
								setTimeout( function() { 
											
																	$('#mensaje').addClass('hidden');
																	$('#btn1, #btn2').prop('disabled', false);

																} , 1000);


							}

				});

			}

		});

		//

		$(document).on('submit', '#frmLinkContraparte', function(e) {
			e.preventDefault();
			var go_ = true;
			if($('.enviar').is(':checked')) {
				if ($('#email').val() == '') {
					go_ = false;
					alert('Indique una dirección de e-mail para enviar el link de acceso.');
				}
			}
			if(go_) {

				$.ajax({
							method : 'post',
							url : '/led/led-link-contraparte-enviar',
							data : $(this).serialize(),
							async : true,
							beforeSend : function() {
								$('#btn1, #btn2').prop('disabled', true);
								$('#loading_msg').removeClass('hidden');
							},
							success : function(data) {
								$('#loading_msg').addClass('hidden');
								
								var msg = JSON.parse(data);
								$('#mensaje').html(msg.mensaje);
								$('#mensaje').removeClass('hidden');
								setTimeout( function() { 
											
																	$('#mensaje').addClass('hidden');
																	$('#btn1, #btn2').prop('disabled', false);

																} , 500);


							}

				});

			}

		});

		// modificar datos de pago

		$(document).on('click', '#modificar-pago', function() {
			//$('#frmPrepagosData [name="valor"]').prop('readonly', false);
			$('#frmPrepagosData [name="status"]').prop('disabled', false);

			if ($('#status').val() == 'approved') {
				$('#frmPrepagosData [name="facturado"]').prop('disabled', false);
				$('#fecha_facturado_ro').hide();
				$('#fecha_facturado_edit').show();
			}

			//$('#frmPrepagosData [name="vigencia"]').prop('readonly', false);
			$('#vigencia_ro').hide();
			$('#vigencia_edit').show();

			//$('#frmPrepagosData [name="fecha_transaccion"]').prop('readonly', false);
            
			/* 08/04/2020 que no se puedan modificar la fecha, ni el Cod de transaccion*/
			/*$('#fecha_transaccion_ro').hide();
			$('#fecha_transaccion_edit').show();
			$('#frmPrepagosData [name="preference_id"]').prop('readonly', false); */
			
			$('#fecha_transaccion_ro').show();
			$('#fecha_transaccion_edit').hide();

			/* Fin 08/04/2020 */

			//$('#frmPrepagosData [name="fecha_confirmacion"]').prop('readonly', false);
			$('#frmPrepagosData [name="motivo"]').prop('readonly', false);
			$('#modificar-pago').prop('disabled', true);
			$('#guardar-pago').prop('disabled', false);
			$('#cancelar-pago').prop('disabled', false);
		});


		
		$(document).on('change', '#facturado', function(evt) {
				evt.preventDefault();
				if ($('#facturado').val() == '0') 
				{
					$('#fecha_facturado').val(''); 	
				}
		}); 

		$(document).on('change', '#status', function(evt) {
			evt.preventDefault();
			if ($('#status').val() == 'approved') {
				$('#frmPrepagosData [name="facturado"]').prop('disabled', false);
				$('#fecha_facturado_ro').hide();
				$('#fecha_facturado_edit').show();
			}
			else
			{
				$('#frmPrepagosData [name="facturado"]').prop('disabled', true);
				$('#facturado').val('0'); 
				$('#fecha_facturado').val(''); 
				$('#fecha_facturado_ro').show();
				$('#fecha_facturado_edit').hide();
			}
		}); 


		$(document).on('submit', '#frmPrepagosData', function(evt) {
			evt.preventDefault();
			if ($('#facturado').val() == '1' && ($('#fecha_facturado').val() == null || $('#fecha_facturado').val() == '')) 
			{
				mensaje ("Falta completar la fecha de la factura",'error');
				return;  
			}
			$.ajax({
						method : 'post',
						data : $(this).serialize(),
						url : '/led/led-prepagos-actualizar-pago',
						dataType : 'json',
						beforeSend : function() {
							$('#pago-loading').show();
							$('#guardar-pago').prop('disabled', true);
							$('#cancelar-pago').prop('disabled', true);
						},
						success : function(response) {
							$('#frmPrepagosData [name="status"]').prop('disabled', true);
							$('#frmPrepagosData [name="facturado"]').prop('disabled', true);
							$('#vigencia_ro').val( response.pago.vigencia );
							$('#fecha_transaccion_ro').val( response.pago.fecha_transaccion );
							$('#fecha_facturado_ro').val( response.pago.fecha_facturado );
							$('#vigencia').val( response.pago.vigencia );
							$('#fecha_transaccion').val( response.pago.fecha_transaccion.substring(0,10) );
							$('#fecha_facturado').val( response.pago.fecha_facturado );
							$('#preference_id').val( response.pago.preference_id );
							$('#motivo').val( response.pago.motivo );

							$('#frmPrepagosData [name="preference_id"]').prop('readonly', true);
							$('#frmPrepagosData [name="motivo"]').prop('readonly', true);

							$('#vigencia_ro').show();
							$('#vigencia_edit').hide();
							$('#fecha_transaccion_ro').show();
							$('#fecha_transaccion_edit').hide();
							$('#fecha_facturado_ro').show();
							$('#fecha_facturado_edit').hide();
							$('#pago-loading').hide();
							$('#modificar-pago').prop('disabled', false);
						}

			});


		});

		$(document).on('click', '#cancelar-pago', function() {
			//$('#frmPrepagosData [name="valor"]').prop('readonly', true);
			$('#frmPrepagosData [name="status"]').prop('disabled', true);
			$('#frmPrepagosData [name="facturado"]').prop('disabled', true);

			//$('#frmPrepagosData [name="vigencia"]').prop('readonly', true);
			$('#vigencia_ro').show();
			$('#vigencia_edit').hide();

			//$('#frmPrepagosData [name="fecha_transaccion"]').prop('readonly', true);
			$('#fecha_transaccion_ro').show();
			$('#fecha_transaccion_edit').hide();

			$('#fecha_facturado_ro').show();
			$('#fecha_facturado_edit').hide();

			$('#frmPrepagosData [name="preference_id"]').prop('readonly', true);
			$('#frmPrepagosData [name="motivo"]').prop('readonly', true);
			$('#modificar-pago').prop('disabled', false);
			$('#guardar-pago').prop('disabled', true);
			$('#cancelar-pago').prop('disabled', true);

		});


    });
</script>

@include('footer')