<?php $r="../";
require_once($r."inc/funciones.php");
$titlepage = 'Cobrar por Pedido';
validNotSession($r);
$spe=$_SESSION['perfil'];
$mysqli = connectDB($r);
roleaccess(1421);
$actionexcel = viewroleaccess(1424);
$row1 = $mysqli->query("SELECT * FROM z_pedidos WHERE  pago < 2 AND estado IN (1,2,3,6) ORDER by codigopedido DESC");
?>
<!DOCTYPE html>
<html lang="es">
  <?php include $r."inc/head.php"; ?>
<body class="fixed-nav sidenav-toggled sticky-footer bg-dark" id="page-top">
  <div class="container">
    <div id="mensaje" style="position:fixed;width:90%;padding-left:10%;top:20px;left:0px;margin:0 auto;z-index:9999;"></div>
  </div>
  <?php include $r."inc/nav.php"; ?>
  
  <div class="content-wrapper">
    <div class="container-fluid">
      <div class="card mb-3">
        <div class="h3 card-header">
          <i class="fa fa-table"></i>  PEDIDOS PENDIENTES POR COBRAR</div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
              <thead>
                <tr>
                  <th>Domiciliario</th>
                  <th>Cliente</th>
                  <th>Fecha entrega</th>
                  <th>Código</th>
                  <th>estado</th>
                  <th>Abono</th>
                  <th>Valor Factura</th>
                  <th>Valor a cobrar</th>
                  <th></th>
                </tr>
              </thead>
              <tfoot>
                <tr>
                  <th>Domiciliario</th>
                  <th>Cliente</th>
                  <th>Fecha entrega</th>
                  <th>Código</th>
                  <th>estado</th>
                  <th>Abono</th>
                  <th>Valor Factura</th>
                  <th>Valor a cobrar</th>
                  <th></th>
                </tr>
              </tfoot>
              <tbody>
                    <?php
                    
                    while($row2 = $row1->fetch_assoc()) {
                    ?>
                      <tr>
                        <td><?php $usuario = sinfo('z_ruteros',$row2["idrutero"]); echo $usuario['nombre']; ?></td>
                        <td><?php $cliente = sinfo('z_clientes',$row2["idcliente"]); echo $cliente['nombre'];?></td>
                        <td><?= $row2["fechaentrega"] ?></td>
                        <td><?= '<b>'.$row2['tipopedido'].'</b> '.$row2['codigopedido']; ?></td>
                        <?php $infopago = sinfo('z_epagos',$row2['pago']); ?><td class="<?= $infopago['color']; ?> h6"><?= $infopago['estado']; ?></td>
                        <td class="text-right h6"><? if(!empty($row2["abono"])){ echo moneda($row2["abono"]); } ?></td>
                        <?php $total = (float)$row2['total'] + (float)$row2['adicional'] - (float)$row2['abono']; ?>
                        <td class="h6 text-primary text-right"><?= moneda((float)$row2['total'] + (float)$row2['adicional']) ?></td>
                        <td class="h6 <? if($total<0){echo 'text-danger';}elseif($total>0){echo 'text-success';}elseif($total=0){echo 'text-warning';}?> text-right"><?= moneda($total) ?></td>
                        <td><i onclick="pagos(<?= round($total); ?>,'<?= $row2["codigopedido"] ?>')" style="cursor:pointer" class="fa fa-money text-success"></i>
                         <?php if($infoestado['id']!=5){if($row2['tipopedido']!='F'){ ?><i onClick="return popitup('../caja/imprimir-1.php?code=<?php echo $row2["codigopedido"] ?>')" class="fa fa-print"></i><? }else{ ?><i onClick="return popitup('../caja/imprimir.php?code=<?php echo $row2["codigopedido"] ?>')" class="fa fa-print"></i><? }} ?></td>
                        </tr>
                    <?php
                    }
                    ?>
              <tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  
    <!-- Modal Pagar-->
    <div class="modal fade" id="ModalPagar" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Pedido Nº: <span id="codepedido"></span></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
              <h3 class="text-center text-success">Valor a pagar:</h3>
              <h3 class="text-center text-success" id="valorapagar"></h3>
              <input form="formcobrar" type="hidden" name="code">
              <input form="formcobrar" type="hidden" name="pago">
              <hr/>
              <h4 class="text-primary">Formas de pago <button type"button" class="btn btn-success float-right" onclick="addmpago()"><i class="fa fa-plus"></i> Agregar</button> </h4>
              <br/>
              <form id="formcobrar" method="POST" action="acciones/pagopedido.php">
              <div id="divpagoo" class="row">
                  <select class="form-control col-6 ml-1"name="medios[]" id="unomedio">
                      <? $sqlmpagos = $mysqli->query("SELECT * FROM z_pagos_medios ORDER BY orden ASC"); while($rowmpagos = $sqlmpagos->fetch_assoc()) { ?><option value="<?= $rowmpagos['id']; ?>"><?= $rowmpagos['medio']; ?></option><? } ?>
                  </select>
                  <input type="number" class="form-control col-5 ml-1 monto" onchange="sumamontos()" id="unomonto"  name="moton[]"  min="1">
              </div>
              <div id="addpago">
                  
              </div>
              </form>
              <h3 class="text-center text-success" id="totalapagar">0</h3>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button id="buttoncobrar" form="formcobrar" type="submit" class="btn btn-success" disabled>Cobrar</button>
          </div>
        </div>
      </div>
    </div>

  <?php include $r."inc/foot.php"; ?>
  <script>
  function popitup(url){
	    newwindow=window.open(url,'name','height=600,width=320'); 
	    if (window.focus) {}
	    return false; 
    }
      function pagos(total,codigo){
          total = parseInt(total);
          $('#valorapagar').html(total);
          $('input[name=code]').val(codigo);
          $('input[name=pago]').val(total);
          $('#codepedido').html(codigo);
          $('#ModalPagar').modal('show');
          $('#addpago').html('');
          $('#unomonto').val(0);
          $('#unomedio').val(1);
          sumamontos();
      }
      function addmpago(){
          $.post( "acciones/addpago.php", function( data ) { $( "#addpago" ).append( data );});
      }
      $('#unomonto').on('keyup', function(){
          sumamontos();
      })
      function sumamontos() {
          var totalsuma = 0;
          var totalapagar = $('input[name=pago]').val();
          $("input.monto").each(function( index ) {
              if($( this ).val() == ''){
                  $( this ).val(0);
              }
              totalsuma = totalsuma + parseInt($( this ).val());
            });
            console.log(totalsuma);
            total = totalapagar-totalsuma;
            console.log(total);
            if(total>0){
                $('#totalapagar').html('<span class="text-danger">Aun Falta '+total+'</span>');
                $('#buttoncobrar').prop("disabled",true);
            }else if(total === 0){
                $('#totalapagar').html('<span class="text-primary">Los Vueltos son '+total+'</span>');
                $('#buttoncobrar').prop("disabled",false);
            }else{
                $('#totalapagar').html('<span class="text-success">Los Vueltos son '+total+'</span>');
                $('#buttoncobrar').prop("disabled",false);
            }
      };
  </script>
  
  <script>
      $('#dataTable').DataTable( {
        "stateSave": true,
        "lengthMenu": [[25, 50, 100, 500, -1], [25, 50, 100, 500, "Todos" ]],
        <?php if($actionexcel){?>"dom": '<"top"lfB>rt<"bottom"ip><"clear">', // Agrega B para los botones
        "buttons": [
            'copy', 'csv', 'excel', 'pdf', 'print'
        // Puedes agregar más botones según tus necesidades
        ],
        <? } ?>
    } );
  </script>
</body>
</html>    