@extends('layouts.app')
@section('content')
<div class="row">
  <div class="col-12">
    <nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item" aria-current="page">Blance Flujo Efectivo</li>
    <li class="breadcrumb-item active" aria-current="page">Cuentas por Cobrar</li>
  </ol>
</nav>
  </div>
</div> 
<div class="row">
	<div class="col-12">
		<div class="card mb-4">
            <div class="card-body">
              <div class="row">
              <div class="col-2">
                  <label>Año</label>
                  <select id="anio" class="form-control" onchange="loadGrid();"> 
                    <option value="2020">2020</option>
                    <option value="2021">2021</option>
                  </select>
                </div>
                <div class="col-2">
                  <label>Periodo</label>
                  <select id="periodo" class="form-control" onchange="loadGrid();"> 
                  @foreach ($data['periodos'] as $peri)
                      <option value="{{ $peri['mes'] }}">{{ $peri['periodo'] }}</option>
                  @endforeach
                  </select>
                </div>
                <div class="col-3">
                  <label>Cliente</label>
                  <select id="cliente" class="form-control" onchange="loadGrid();">
                    <option value="0">Todos</option>
                    @foreach ($data['clientes'] as $cliente)
                      <option value="{{ $cliente->id }}">{{ $cliente->nombre }} ({{ $cliente->rfc }})</option>
                    @endforeach
                  </select>
                </div>

              </div>
              <br>
               <div class="row">
               	<div class="col-12">
               		<table class="table table-inverse" id="gridFacturas">
               			<thead>
               				<tr>
                        <th>ID</th>
               					<th>Cliente</th>
               					<th>RFC</th>
                        <th>Folio</th>
                        <th>UUID</th>
                        <th>Monto</th>
                        <th>Saldo</th>
                        <th>Estatus</th>
                        <th>Pagos</th>
               				</tr>
               			</thead>
               			<tbody>
               		
               			</tbody>
               		</table>
               	</div>
               </div>
            </div>
        </div>
	</div>
</div>

<div class="modal fade" id="cargando">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">
            <h4 class="modal-title">Cargando</h4>
         </div>
         <div class="modal-body">
            <div class="row">
               <div class="col-12 align-items-center">
                  <div align="center">
                     <img src="{{ asset('img/loading.gif') }}" width="400">
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>


<div class="modal fade" id="modalPagos">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-info">
        <h4 class="modal-title">Pagos</h4>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-12">
            <h3 id="clienteLabelPagos"></h3>
            <input type="hidden" id="idFactHidden">
          </div>
        </div>
        <hr>  
        <div class="row">
          <div class="col-12">
            <h5>Aplicar Pago</h5>
          </div>
        </div>
        <div class="row">
          <div class="col-9">
            <label>Importe</label>
            <input type="number" class="form-control" id="imporPago">
          </div>
          <div class="col-3">
            <br>
            <button class="btn btn-block btn-success" onclick="aplicaPago();">Aplicar</button>
          </div>
        </div>
        <hr>
        <div class="row">
          <div class="col-12">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Importe</th>
                  <th>Fecha</th>
                  <th>Eliminar</th>
                </tr>
              </thead>
              <tbody id="tablePagosBody">

              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
        <!--<button type="button" class="btn btn-primary">Save changes</button>-->
      </div>
    </div>
  </div>
</div>

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

      //loadGrid();
   });

  function loadGrid(){
      var cliente = $('#cliente').val();
      var anio = $('#anio').val();
      var periodo = $('#periodo').val();
      //var fechas = $('#rango').val()
       //$('#').DataTable();
      $('#gridFacturas').dataTable().fnDestroy();
      $('#gridFacturas').DataTable( {
           processing: true,
           responsive: true,
           //serverSide: true,
           ajax: {
               url: "get_cxc",
               type: "POST",
               data: {
                cliente: cliente,
                anio : anio,
                periodo : periodo,
                //rango: fechas
              },
           },
           columns: [
               { data: "id_cliente" },
               { data: "nombre_cliente" },
               { data: "rfc_receptor" },
               { data: "SerieFolio" },
               { data: "uuid" },
               { data: "monto" },
               { data: "saldo" },
               { data: "estatus" },
               { data: "acciones" },
           ],
           order: [[0,"desc"]]
       } );
      
   }
  function pagarFact(idfactura,idCliente){
    $.ajax({
      url: 'get_pagos_fact',
      type: 'POST',
      dataType: 'json',
      data: {
        idfactura: idfactura,
        idCliente : idCliente
      },
    })
    .done(function(resp) {
      console.log("success");
      $('#idFactHidden').val(idfactura)
      $('#clienteLabelPagos').html(resp.cliente)
      $('#imporPago').val('')
      $('#tablePagosBody').empty()
      html = '';
      $.each(resp.data, function(index, val) {
        html +='<tr id="pago_'+val.id+'">';
        html +='<td>'+val.id+'</td>';
        html +='<td>$'+val.importe+'</td>';
        html +='<td>'+val.fecha+'</td>';
        html +='<td align="center"><button class="btn btn-danger" onclick="eliminaPago('+val.id+')">Eliminar</button></td>';
        html +='</tr>'
      });

      $('#tablePagosBody').append(html)
      $('#modalPagos').modal()
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
    
  }
  function aplicaPago(){
    var fact = $('#idFactHidden').val()
    var importe = $('#imporPago').val()
    if(importe < 1){
      alert('El importe debe ser mayor a 0.')
      return false;
    }
    $.ajax({
      url: 'aplica_pago',
      type: 'POST',
      dataType: 'json',
      data: {
        importe: importe,
        idfactura: fact
      },
    })
    .done(function(resp) {
      console.log("success");
      if(resp.id > 0){
        alert(resp.mensaje);
        $('#modalPagos').modal('hide');
        loadGrid();
      }
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
    

  }
  function eliminaPago(id){
    $.ajax({
      url: 'elimina_pago',
      type: 'POST',
      dataType: 'json',
      data: {id: id},
    })
    .done(function(resp) {
      console.log("success");
      if(resp.estatus==1){
        alert('Se elimino correctmente')
        $('#pago_'+id).remove();
        loadGrid();
      }
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
    
  }
</script>
@endsection