<?
$r = "../";
require_once($r."inc/funciones.php");
validNotSession($r);
$sql="";
$i=0;
foreach ($_GET as $key => $value)
{   
    $sqlinner = "";
    if($key!="fecha1" && $key!='fecha2' && $key!='id' && $key!='estado' && $key!='mpago'){
        if($value!=""){$sql .= "z_pedidos.$key='$value' AND ";}
    }
    
    if($key=="fecha1" or $key=='fecha2'){
        if($key=="fecha1"){
            if($value!=""){
            $fecha1=$value;
            $fecha2=$value;
            $fechai= "z_pagos.fecha BETWEEN '$fecha1 00:00:00' AND '$fecha2 23:59:59' AND ";
            $afechai= "z_abonos.fecha BETWEEN '$fecha1 00:00:00' AND '$fecha2 23:59:59' AND ";
            
            }
        }
        if($key=="fecha2"){
            if($value!=""){
            $fecha2=$value;
            $fechaf= "z_pagos.fecha BETWEEN '$fecha1 00:00:00' AND '$fecha2 23:59:59' AND ";
            $afechaf= "z_abonos.fecha BETWEEN '$fecha1 00:00:00' AND '$fecha2 23:59:59' AND ";
            }
        }
    }
    if($key=='estado'){
        foreach ($_GET['estado'] as $key2 => $value2){
            if($i!='0'){
                $sql2 .= "OR z_pedidos.estado='$value2' ";
                $i++;
            }else{
                $sql2 .= "z_pedidos.estado='$value2' ";
                $i++;
            };
        }$sql2 .=' AND ';
    }
    $i=0;
    if($key=='mpago'){
        foreach ($_GET['mpago'] as $key3 => $value3){
            if($i!='0'){
                $sqlmpago .= "OR z_pagos.idmedio='$value3' ";
                $sqlmpagoa .= "OR z_abonos.idmedio='$value3' ";
                $i++;
            }else{
                $sqlmpago .= "( z_pagos.idmedio='$value3' ";
                $sqlmpagoa .= "( z_abonos.idmedio='$value3' ";
                $i++;
            };
        }$sqlmpago .=') AND ';$sqlmpagoa .=') AND ';
    }
    $sqlid= "z_pagos.monto!=0";
    $sqlida= "z_abonos.abono!=0";
   
}
if($fechaf==""){$sql.=$fechai;}else{$sql.=$fechaf;}
if($afechaf==""){$asql.=$afechai;}else{$asql.=$afechaf;}
$mysqli = connectDB($r);
$row1 = $mysqli->query("SELECT z_pagos.idmedio, z_pagos.monto, z_pagos.fecha AS 'pfecha', z_pedidos.iduser, z_pedidos.idcliente, z_pedidos.codigopedido, z_pedidos.idrutero, z_pedidos.fecha AS 'fecha', z_pedidos.total, z_pedidos.pago FROM z_pagos INNER JOIN z_pedidos ON z_pagos.idpedido=z_pedidos.codigopedido WHERE $sql2 $sql $sqlmpago $sqlid");

$row3 = $mysqli->query("SELECT z_abonos.idmedio, z_abonos.abono, z_abonos.fecha AS 'pfecha', z_pedidos.iduser, z_pedidos.idcliente, z_pedidos.codigopedido, z_pedidos.idrutero, z_pedidos.fecha AS 'fecha', z_pedidos.total, z_pedidos.pago FROM z_abonos INNER JOIN z_pedidos ON z_abonos.codigopedido=z_pedidos.codigopedido WHERE $sql2 $asql $sqlmpagoa $sqlida");
?>
<!DOCTYPE html>
<html lang="en">
  <?php include $r."inc/head.php"; ?>
<body class="fixed-nav sidenav-toggled sticky-footer bg-dark" id="page-top">
  <?php include $r."inc/nav.php"; ?>
  <style>.sweet-alert{
      width: 80%;
    margin-left: -40%;
}</style>
  <div class="content-wrapper">
    <div class="container-fluid">
      <div class="card mb-3">
        <div class="h3 card-header">
          <i class="fa fa-table"></i> RESULTADO CONSULTA</div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
              <thead>
                <tr>
                  <th>Usuario</th>
                  <th>Cliente</th>
                  <th>Domiciliario</th>
                  <th>Fecha pedido </th>
                  <th>Fecha pago </th>
                  <th>Codigo </th>
                  <th>Pago </th>
                  <th>Medio </th>
                  <th>Valor pagado</th>
                  <th>valor pedido</th>
                  <th>Acción</th>
                </tr>
              </thead>
              <tbody>
                    <?php while($row2 = $row1->fetch_assoc()) { ?>
                      <tr>
                        <td><?php $usuario = suser($row2["iduser"]); echo $usuario['nombre']; ?></td>
                        <td><?php $cliente = sclien($row2["idcliente"]); echo $cliente['nombre'];?></td>
                        <td><?php $rutero = srute($row2["idrutero"]); echo $rutero['nombre']; ?></td>
                        <td><?php echo $row2["fecha"] ?></td>
                        <td><?= $row2['pfecha']; ?></td>
                        <td><?php echo "<b>".$row2["tipopedido"]." </b>".$row2["codigopedido"] ?></td>
                        <? $subtotal = ((int)$row2['total']+(int)$row2['adicional']); ?>
                        <?php $infopago = sinfo('z_epagos',$row2['pago']); ?><td class="<?= $infopago['color'];?>"><?= $infopago['estado'];?></td>
                        <?php $infomediopago = sinfo('z_pagos_medios',$row2['idmedio']); ?><td><?= $infomediopago['medio'];?></td>
                        
                        <td><?= moneda($row2['monto']); ?></td>
                        <?php   if($row2["pago"]!=1){ ?>
                        <td class="h6 <? if($subtotal<0){echo 'text-danger';}elseif($subtotal>0){echo 'text-success';}elseif($subtotal=0){echo 'text-warning';}?> text-right"><?= moneda($subtotal); ?></td>
                        <? }else{echo '<td><spam class="h6 text-warning text-right">'.moneda($subtotal).'</spam></td>';}?>
                        
                    <td width="20px">
                        <?php if($infoestado['id']!=5){if($row2['tipopedido']!='F'){ ?>
                        
                        <a class="btn_default text-primary h5"  onClick="return popitup('../caja/imprimir-1.php?code=<?php echo $row2["codigopedido"] ?>')" href="../caja/imprimir-1.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>
                        <?php } else{ ?>
                        
                        <a class="btn_default text-danger h5"  onClick="return popitup('../caja/imprimir.php?code=<?php echo $row2["codigopedido"] ?>')" href="../caja/imprimir.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>
                        <?php }} ?>
                    <!--<a class="btn_default text-success h5"  href="my.bluetoothprint.scheme://https://quimiforen.com/admin/movil/a.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>-->
                            <? $code = $row2["codigopedido"]; $sqlpago = $mysqli->query("SELECT id FROM `z_pagos` WHERE idpedido = $code"); if($sqlpago->num_rows > 0){ ?><i onclick="hpay('<?= $code ?>')" class="fa fa-list text-secondary ml-1" style="cursor:pointer"></i><? } ?>
                            <? $sqlabonos = $mysqli->query("SELECT id FROM `z_abonos` WHERE codigopedido = $code"); if($sqlabonos->num_rows > 0){ ?><i onclick="habonos(<?= $code ?>,<?= $subtotal; ?>)" class="fa fa-history text-secondary ml-1" style="cursor:pointer"></i><? } ?>
                            </td>
                        </tr>
                    <?php 
                    
                    $total= $total + $subtotal;
                    $total2=$total2 + $row2['monto'];
                    }
                    ?>
                    <?php while($row2 = $row3->fetch_assoc()) { ?>
                      <tr>
                        <td><?php $usuario = suser($row2["iduser"]); echo $usuario['nombre']; ?></td>
                        <td><?php $cliente = sclien($row2["idcliente"]); echo $cliente['nombre'];?></td>
                        <td><?php $rutero = srute($row2["idrutero"]); echo $rutero['nombre']; ?></td>
                        <td><?php echo $row2["fecha"] ?></td>
                        <td><?= $row2['pfecha']; ?></td>
                        <td><?php echo "<b>".$row2["tipopedido"]." </b>".$row2["codigopedido"] ?></td>
                        <? $subtotal = ((int)$row2['total']+(int)$row2['adicional']); ?>
                        <?php $infopago = sinfo('z_epagos',$row2['pago']); ?><td class="<?= $infopago['color'];?>"><?= $infopago['estado'];?></td>
                        <?php $infomediopago = sinfo('z_pagos_medios',$row2['idmedio']); ?><td><?= $infomediopago['medio'];?></td>
                        
                        <td class="text-primary"><?= moneda($row2['abono']); ?></td>
                        <?php   if($row2["pago"]!=1){ ?>
                        <td class="h6 <? if($subtotal<0){echo 'text-danger';}elseif($subtotal>0){echo 'text-success';}elseif($subtotal=0){echo 'text-warning';}?> text-right"><?= moneda($subtotal); ?></td>
                        <? }else{echo '<td><spam class="h6 text-warning text-right">'.moneda($subtotal).'</spam></td>';}?>
                        
                    <td width="20px">
                        <?php if($infoestado['id']!=5){if($row2['tipopedido']!='F'){ ?>
                        
                        <a class="btn_default text-primary h5"  onClick="return popitup('../caja/imprimir-1.php?code=<?php echo $row2["codigopedido"] ?>')" href="../caja/imprimir-1.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>
                        <?php } else{ ?>
                        
                        <a class="btn_default text-danger h5"  onClick="return popitup('../caja/imprimir.php?code=<?php echo $row2["codigopedido"] ?>')" href="../caja/imprimir.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>
                        <?php }} ?>
                    <!--<a class="btn_default text-success h5"  href="my.bluetoothprint.scheme://https://quimiforen.com/admin/movil/a.php?code=<?php echo $row2["codigopedido"] ?>" target="_blank"><i class="fa fa-print"></i></a>-->
                            <? $code = $row2["codigopedido"]; $sqlpago = $mysqli->query("SELECT id FROM `z_pagos` WHERE idpedido = $code"); if($sqlpago->num_rows > 0){ ?><i onclick="hpay('<?= $code ?>')" class="fa fa-list text-secondary ml-1" style="cursor:pointer"></i><? } ?>
                            <? $sqlabonos = $mysqli->query("SELECT id FROM `z_abonos` WHERE codigopedido = $code"); if($sqlabonos->num_rows > 0){ ?><i onclick="habonos(<?= $code ?>,<?= $subtotal; ?>)" class="fa fa-history text-secondary ml-1" style="cursor:pointer"></i><? } ?>
                            </td>
                        </tr>
                    <?php 
                    
                    $total= $total + $subtotal;
                    $total2=$total2 + $row2['abono'];
                    }
                    ?>
              <tbody>
                  
              <tfoot>
                <tr>
                  <th colspan="7"></th>
                  <th>TOTAL</th>
                  <th class=" text-right text-primary"><?= moneda($total2); ?></th>
                  <th class=" text-right text-primary"><?= moneda($total); ?></th>
                  <th><?= moneda($total-$total2); ?></th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>
      <a class="btn btn-primary float-left" href="javascript:history.back()">Atras</a>
    </div>
  </div>
  <?php include $r."inc/foot.php"; ?>
 
<script>
    function popitup(url){
	    newwindow=window.open(url,'name','height=600,width=320'); 
	    if (window.focus) {newwindow.print();}
	    return false; 
    }
    function hpay(code){
        $.post( "acciones/infopago.php", { code: code })
          .done(function( data ) {
          swal({ html:true, title:'<i>'+code+'</i>', text:'<div>'+data+'</div>'});
          });
        
    }
    function habonos(code,total){
        let num = new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'COP' }).format(total);
        $.post( "acciones/infoabonos.php", { code: code, total: total })
          .done(function( data ) {
          swal({ html:true, title:'#<i>'+code+' </i> - Total : <i>'+num+'</i>', text:'<div>'+data+'</div>'});
          });
        
    }
</script> 
<script>
$('#dataTable').DataTable( {
        "order": [[ 3, "desc" ]],
        "lengthMenu": [[100, 500, 1000, -1], [100, 500, 1000, "All"]]
    } );
  </script>
</body>
</html>   