<?php
session_start();
require('code39.php');
require('fpdi/fpdi.php');
require('conexion.php');

date_default_timezone_set('America/Mazatlan');

function getSubString($string, $length=NULL)
{
    //Si no se especifica la longitud por defecto es 50
    if ($length == NULL)
        $length = 30;
    //Primero eliminamos las etiquetas html y luego cortamos el string
    $stringDisplay = substr(strip_tags($string), 0, $length);
    //Si el texto es mayor que la longitud se agrega puntos suspensivos
    if (strlen(strip_tags($string)) > $length)
        $stringDisplay .= ' ...';
    return $stringDisplay;
}

function num2letras($num, $fem = false, $dec = true) { 
   $matuni[2]  = "dos"; 
   $matuni[3]  = "tres"; 
   $matuni[4]  = "cuatro"; 
   $matuni[5]  = "cinco"; 
   $matuni[6]  = "seis"; 
   $matuni[7]  = "siete"; 
   $matuni[8]  = "ocho"; 
   $matuni[9]  = "nueve"; 
   $matuni[10] = "diez"; 
   $matuni[11] = "once"; 
   $matuni[12] = "doce"; 
   $matuni[13] = "trece"; 
   $matuni[14] = "catorce"; 
   $matuni[15] = "quince"; 
   $matuni[16] = "dieciseis"; 
   $matuni[17] = "diecisiete"; 
   $matuni[18] = "dieciocho"; 
   $matuni[19] = "diecinueve"; 
   $matuni[20] = "veinte"; 
   $matunisub[2] = "dos"; 
   $matunisub[3] = "tres"; 
   $matunisub[4] = "cuatro"; 
   $matunisub[5] = "quin"; 
   $matunisub[6] = "seis"; 
   $matunisub[7] = "sete"; 
   $matunisub[8] = "ocho"; 
   $matunisub[9] = "nove"; 

   $matdec[2] = "veint"; 
   $matdec[3] = "treinta"; 
   $matdec[4] = "cuarenta"; 
   $matdec[5] = "cincuenta"; 
   $matdec[6] = "sesenta"; 
   $matdec[7] = "setenta"; 
   $matdec[8] = "ochenta"; 
   $matdec[9] = "noventa"; 
   $matsub[3]  = 'mill'; 
   $matsub[5]  = 'bill'; 
   $matsub[7]  = 'mill'; 
   $matsub[9]  = 'trill'; 
   $matsub[11] = 'mill'; 
   $matsub[13] = 'bill'; 
   $matsub[15] = 'mill'; 
   $matmil[4]  = 'millones'; 
   $matmil[6]  = 'billones'; 
   $matmil[7]  = 'de billones'; 
   $matmil[8]  = 'millones de billones'; 
   $matmil[10] = 'trillones'; 
   $matmil[11] = 'de trillones'; 
   $matmil[12] = 'millones de trillones'; 
   $matmil[13] = 'de trillones'; 
   $matmil[14] = 'billones de trillones'; 
   $matmil[15] = 'de billones de trillones'; 
   $matmil[16] = 'millones de billones de trillones'; 
   
   //Zi hack
   $float=explode('.',$num);
   $num=$float[0];

   $num = trim((string)@$num); 
   if ($num[0] == '-') { 
      $neg = 'menos '; 
      $num = substr($num, 1); 
   }else 
      $neg = ''; 
   while ($num[0] == '0') $num = substr($num, 1); 
   if ($num[0] < '1' or $num[0] > 9) $num = '0' . $num; 
   $zeros = true; 
   $punt = false; 
   $ent = ''; 
   $fra = ''; 
   for ($c = 0; $c < strlen($num); $c++) { 
      $n = $num[$c]; 
      if (! (strpos(".,'''", $n) === false)) { 
         if ($punt) break; 
         else{ 
            $punt = true; 
            continue; 
         } 

      }elseif (! (strpos('0123456789', $n) === false)) { 
         if ($punt) { 
            if ($n != '0') $zeros = false; 
            $fra .= $n; 
         }else 

            $ent .= $n; 
      }else 

         break; 

   } 
   $ent = '     ' . $ent; 
   if ($dec and $fra and ! $zeros) { 
      $fin = ' coma'; 
      for ($n = 0; $n < strlen($fra); $n++) { 
         if (($s = $fra[$n]) == '0') 
            $fin .= ' cero'; 
         elseif ($s == '1') 
            $fin .= $fem ? ' una' : ' un'; 
         else 
            $fin .= ' ' . $matuni[$s]; 
      } 
   }else 
      $fin = ''; 
   if ((int)$ent === 0) return 'Cero ' . $fin; 
   $tex = ''; 
   $sub = 0; 
   $mils = 0; 
   $neutro = false; 
   while ( ($num = substr($ent, -3)) != '   ') { 
      $ent = substr($ent, 0, -3); 
      if (++$sub < 3 and $fem) { 
         $matuni[1] = 'una'; 
         $subcent = 'as'; 
      }else{ 
         $matuni[1] = $neutro ? 'un' : 'uno'; 
         $subcent = 'os'; 
      } 
      $t = ''; 
      $n2 = substr($num, 1); 
      if ($n2 == '00') { 
      }elseif ($n2 < 21) 
         $t = ' ' . $matuni[(int)$n2]; 
      elseif ($n2 < 30) { 
         $n3 = $num[2]; 
         if ($n3 != 0) $t = 'i' . $matuni[$n3]; 
         $n2 = $num[1]; 
         $t = ' ' . $matdec[$n2] . $t; 
      }else{ 
         $n3 = $num[2]; 
         if ($n3 != 0) $t = ' y ' . $matuni[$n3]; 
         $n2 = $num[1]; 
         $t = ' ' . $matdec[$n2] . $t; 
      } 
      $n = $num[0]; 
      if ($n == 1) { 
         $t = ' ciento' . $t; 
      }elseif ($n == 5){ 
         $t = ' ' . $matunisub[$n] . 'ient' . $subcent . $t; 
      }elseif ($n != 0){ 
         $t = ' ' . $matunisub[$n] . 'cient' . $subcent . $t; 
      } 
      if ($sub == 1) { 
      }elseif (! isset($matsub[$sub])) { 
         if ($num == 1) { 
            $t = ' mil'; 
         }elseif ($num > 1){ 
            $t .= ' mil'; 
         } 
      }elseif ($num == 1) { 
         $t .= ' ' . $matsub[$sub] . '?n'; 
      }elseif ($num > 1){ 
         $t .= ' ' . $matsub[$sub] . 'ones'; 
      }   
      if ($num == '000') $mils ++; 
      elseif ($mils != 0) { 
         if (isset($matmil[$sub])) $t .= ' ' . $matmil[$sub]; 
         $mils = 0; 
      } 
      $neutro = true; 
      $tex = $t . $tex; 
   } 
   $tex = $neg . substr($tex, 1) . $fin; 
   //Zi hack --> return ucfirst($tex);
   $end_num=ucfirst($tex).' pesos '.$float[1].'/100 M.N.';
   return $end_num; 
}







$nom = $_SESSION['nom_admin'];
$iduser = $_SESSION['id_user'];
$suc = $_SESSION['IdSuc'];
$tipou= $_SESSION['tipouser'];

$desde = $_GET['desde'];
$hasta = $desde;
$tipop = $_GET['tipo'];
$sucbus = $_GET['sucbus'];
  $fechai = date('Y-m-d H:i:s');
  $fechap = date('Y-m-d');

if($suc == 1){
    $sucn = 'SUCURSAL CULIACAN';
}else if ($suc == 2){
    $sucn = 'SUCURSAL MAZATLAN';
}else if($suc == 3){
    $sucn = 'SUCURSAL HERMOSILLO';
}
if($sucbus == 0){
  if($tipop != 0){
    //$registro = mysqli_query($conexion,"SELECT * FROM factGDL JOIN  ORDER BY IdCliente ASC ");
    $registro = mysqli_query($conexion,"SELECT V.IdMovimiento AS 'Consecutivo',V.Fecha AS 'Fecha', V.Serie AS 'Serie', V.FolioVenta AS 'Folio' ,V.IdSucursal AS 'Sucursal',V.Total AS 'Total',V.Anticipo AS 'Anticipo',V.Saldo AS 'Saldo',V.IdUsuario,V.Descripcion,V.TipoMovimiento,V.FechaB,D.TipoFolio FROM Movimientos V 

      JOIN Ventas D ON D.Serie = V.Serie AND D.FolioVenta = V.FolioVenta

        WHERE V.Activo = 1 AND V.FechaB BETWEEN '$desde' AND '$hasta' AND V.TipoMovimiento != '4' AND D.TipoFolio = '$tipop'  ORDER BY V.Fecha ASC");
  }else if($tipop == 0){
    $registro = mysqli_query($conexion,"SELECT V.IdMovimiento AS 'Consecutivo',V.Fecha AS 'Fecha', V.Serie AS 'Serie', V.FolioVenta AS 'Folio' ,V.IdSucursal AS 'Sucursal',V.Total AS 'Total',V.Anticipo AS 'Anticipo',V.Saldo AS 'Saldo',V.IdUsuario,V.Descripcion,V.TipoMovimiento,V.FechaB FROM Movimientos V 


        WHERE V.Activo = 1 AND V.FechaB BETWEEN '$desde' AND '$hasta' AND V.TipoMovimiento != '4'   ORDER BY V.Fecha ASC");
  }
}else if($sucbus != 0){
  if($tipop != 0){
    //$registro = mysqli_query($conexion,"SELECT * FROM factGDL JOIN  ORDER BY IdCliente ASC ");
    $registro = mysqli_query($conexion,"SELECT V.IdMovimiento AS 'Consecutivo',V.Fecha AS 'Fecha', V.Serie AS 'Serie', V.FolioVenta AS 'Folio' ,V.IdSucursal AS 'Sucursal',V.Total AS 'Total',V.Anticipo AS 'Anticipo',V.Saldo AS 'Saldo',V.IdUsuario,V.Descripcion,V.TipoMovimiento,V.FechaB,D.TipoFolio FROM Movimientos V 

      JOIN Ventas D ON D.Serie = V.Serie AND D.FolioVenta = V.FolioVenta

        WHERE V.Activo = 1 AND V.FechaB BETWEEN '$desde' AND '$hasta' AND V.TipoMovimiento != '4' AND D.TipoFolio = '$tipop' AND V.IdSucursal ='$sucbus'  ORDER BY V.Fecha ASC");
  }else if($tipop == 0){
    $registro = mysqli_query($conexion,"SELECT V.IdMovimiento AS 'Consecutivo',V.Fecha AS 'Fecha', V.Serie AS 'Serie', V.FolioVenta AS 'Folio' ,V.IdSucursal AS 'Sucursal',V.Total AS 'Total',V.Anticipo AS 'Anticipo',V.Saldo AS 'Saldo',V.IdUsuario,V.Descripcion,V.TipoMovimiento,V.FechaB FROM Movimientos V 


        WHERE V.Activo = 1 AND V.FechaB BETWEEN '$desde' AND '$hasta' AND V.TipoMovimiento != '4' AND V.IdSucursal ='$sucbus'  ORDER BY V.Fecha ASC");
  }
}
  //CREAMOS NUESTRA VISTA Y LA DEVOLVEMOS AL AJAX
  $contador = mysqli_num_rows($registro);
  ;

/*
  $gasto = mysqli_query($conexion,"SELECT * FROM Ventas WHERE FolioVenta = '$folio' AND Serie = '$serie' AND Activo = 1");
  $v = mysqli_fetch_array($gasto);




  $tipoord = $v['TipoOrden'];
  if($tipoord == 1){
    $tip = 'Orden';
  }else if($tipoord == 2){
    $tip = 'Cotizacion';
  }
  $idu = $v['IdVendedor'];
  $nombrea = mysqli_query($conexion,"SELECT * FROM Usuarios WHERE IdUsuario = '$idu' ");
  $usu = mysqli_fetch_array($nombrea);


  $usuario = $usu['Nombre'].' '.$usu['Apellidos'];
  if($idu == 5){
    $usuario = 'Martha Nuñez';
  }
  $tipofolio = $v['TipoFolio'];
  $fechaventa = $v['FechaVenta'];
  $idsuc = $v['IdSucursal'];
  if($idsuc == 1){
      $sucn = 'SUCURSAL CULIACAN';
  }else if ($idsuc == 2){
      $sucn = 'SUCURSAL MAZATLAN';
  }else if($idsuc == 3){
      $sucn = 'SUCURSAL HERMOSILLO';
  }
  $idc = $v['IdCliente'];
  $cl = mysqli_query($conexion,"SELECT * FROM Clientes WHERE IdCliente = '$idc'");
  $c = mysqli_fetch_array($cl);

  $nomC = $c['Nombre'];
  $domC = $c['Domicilio'];
  $rfcC = $c['RFC'];
  $celC = $c['Celular'];
  $telC = $c['Telefono'];
  $ciuC = $c['Ciudad'];
  $sucC = $c['IdSucursal'];
  $tipoC = $c['TipoCliente'];
  if($tipoC == 1){
    $tipoCliente = 'Mostrador';
  }else if($tipoC == 2){
    $tipoCliente = 'Fotografo';
  }

  $subt = $v['Subtotal'];
  $dcto = $v['Descuento'];
  $total = $v['Total'];
  $anti = $v['Anticipo'];
  $saldo = $v['Saldo'];
  $obs = $v['Obs'];
  $hrent = $v['HoraEntrega'];
  $fechaent = $v['FechaEntrega'];
*/
  if($sucbus == 0){
    $sn = 'GLOBAL';
  }else if($sucbus == 1){
    $sn = 'CULIACAN';
  }else if($sucbus == 2){
    $sn = 'MAZATLAN';
  }else if($sucbus == 3){
    $sn = 'HERMOSILLO';
  }
  if($tipop == 0){
    $tn = 'GENERAL '.$sn;
  }else if($tipop == 1){
    $tn = 'FOLIOS FISCALES '.$sn;
  }else if($tipop == 2){
    $tn = 'NOTAS DE VENTA '.$sn;
  }


$k = mysqli_query($conexion,"SELECT * FROM Arqueo WHERE Fecha = '$desde' AND IdSucursal = '$sucbus' order by IdArqueo desc limit 1");
if(mysqli_num_rows($k)>0){
$a = mysqli_fetch_array($k);
$cod = $a['IdArqueo'];
$mpeso = $a['Muno'];
$mdos = $a['Mdos'];
$mcin = $a['Mcinco'];
$mdiez = $a['Mdiez'];
$mveinte = $a['Mveinte'];
$bveinte = $a['Bveinte'];
$bcin = $a['Bcincuenta'];
$bcien = $a['Bcien'];
$bdosc = $a['Bdosc'];
$bquin = $a['Bquin'];
$cheque = $a['cheque'];
$totala = $a['Saldo'];
$totali = $a['SaldoInicial'];
$flag = 1;
}else{
    $flag = 2;
}


$j = mysqli_query($conexion,"SELECT * FROM Movimientos WHERE FechaB BETWEEN '$desde' AND '$hasta' AND Activo = 1 AND IdSucursal ='$sucbus'");
$totale = 0;
while($f = mysqli_fetch_array($j)){
    $anti = $f['Anticipo'];
    $totale = $anti + $totale;
    $tipomov = $f['TipoMovimiento'];
    $mp = $f['MetodoPago'];
    if($tipomov == 2){
        $salida += $f['Total'];
    }else{
        if($mp == 1){
            $tefe = $tefe + $anti;
        }else if($mp== 2){
            $tch = $tch + $anti;
        }else if($mp == 3){
            $ttar = $ttar + $anti;
        }
    }

}
$totalf = ($totali + $tefe) - $salida;
$dif = $totala - $totalf;
$totalf = number_format($totalf,2,'.',',');
$totale = number_format($totale,2,'.',',');
$salidas = number_format($salida,2,'.',',');
$efectivo = number_format($tefe,2,'.',',');
$cheques = number_format($tch,2,'.',',');
$tarj = number_format($ttar,2,'.',',');

$totala = number_format($totala,2,'.',',');
$totali = number_format($totali,2,'.',',');


$dif = number_format($dif,2,'.',',');

$pdf = new PDF_Code39('P');
$pdf->AddPage();

// PARTE DE INFORMACION
$pdf->SetFont('Arial', '', 9);
$pdf->Image('imagenes/logo.jpg' , 10 ,10, 50 , 30,'JPG');


$newDate = date("d-m-Y", strtotime($desde));
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetY(19);
$pdf->Cell(200, 8, utf8_decode($tn), 0,0,C);
$pdf->Ln(6);
$pdf->Cell(200, 8, utf8_decode('ARQUEO DEL DIA '.$newDate), 0,0,C);
$pdf->Ln(8);
$pdf->SetFont('Arial', 'U', 10);
$pdf->Cell(100, 8, 'ARQUEO', 0,0,R);
$pdf->Cell(90, 8, 'Fecha de impresion: '.$fechai, 0,0,R);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Ln(8);
$pdf->Cell(40, 6, 'M1: '.$mpeso, 0,0,C);
$pdf->Cell(40, 6, 'M2: '.$mdos, 0,0,C);
$pdf->Cell(40, 6, 'M5: '.$mcin, 0,0,C);
$pdf->Cell(40, 6, 'M10: '.$mdiez, 0,0,C);
$pdf->Cell(40, 6, 'M20: '.$mveinte, 0,0,C);
$pdf->Ln(6);
$pdf->Cell(40, 6, 'B20: '.$bveinte, 0,0,C);
$pdf->Cell(40, 6, 'B50: '.$bcin, 0,0,C);
$pdf->Cell(40, 6, 'B100: '.$bcien, 0,0,C);
$pdf->Cell(40, 6, 'B200: '.$bdosc, 0,0,C);
$pdf->Cell(40, 6, 'B500: '.$bquin, 0,0,C);
$pdf->Ln(6);
$pdf->Cell(190, 8, utf8_decode('RESUMEN'), 0,0,C);
$pdf->Ln(6);
$pdf->Cell(63, 8, 'Efectivo: $'.$efectivo, 0,0,C);
$pdf->Cell(63, 8, 'Depositos: $'.$cheques, 0,0,C);
$pdf->Cell(63, 8, 'Tarjeta: $'.$tarj, 0,0,C);
$pdf->Ln(6);
$pdf->Cell(63, 8, 'Total Entradas: $'.$totale, 0,0,C);
$pdf->Cell(63, 8, 'Saldo inicial: $'.$totali, 0,0,C);
$pdf->Cell(63, 8, 'Salidas: $'.$salidas, 0,0,C);
$pdf->Ln(6);
$pdf->Cell(63, 8, 'Total Caja: $'.$totalf, 0,0,C);
$pdf->Cell(63, 8, 'Total Arqueo: $'.$totala, 0,0,C);
$pdf->Cell(63, 8, 'Diferencia: $'.$dif, 0,0,C);
$pdf->SetY(80);
$pdf->Cell(18, 8, 'Fecha', 1,0,C);
$pdf->Cell(100, 8, 'Descripcion', 1,0,C);
$pdf->Cell(18, 8, 'Venta', 1,0,C);
$pdf->Cell(18, 8, 'Entrada', 1,0,C);
$pdf->Cell(18, 8, 'Saldo', 1,0,C);
$pdf->Cell(18, 8, 'Salida', 1,0,C);
$pdf->Ln(8);
$pdf->SetFont('Arial', 'B', 8);
$y = $pdf->GetY();


while($d = mysqli_fetch_array($registro)){
  $ea = 0;
  $total = 0;
  $saldo = 0;
  $i = 0;
  $fecha= $d['FechaB'];
  $des = $d['Descripcion'];
  $i = $d['Anticipo'];
  $s = $d['Serie'];
  $f = $d['Folio'];
  
  $tipo = $d['TipoMovimiento'];
  if($tipo == 2){
    $ea = $d['Total'];
  }else{
    $total = $d['Total'];
    $saldo = $d['Saldo'];
  }
  $suc= $d['Sucursal'];
  if($suc == 1){
      $sucn = 'CUL';
  }else if ($suc == 2){
      $sucn = 'MAZ';
  }else if($suc == 3){
      $sucn = 'HER';
  }
  
  $id = $d['Consecutivo'];

  $subtotalg = $subtotalg + $i;
  $subtotalu = $subtotalu + $ea;
  $subtotalt = $subtotalt + $total;
  $subtotals = $subtotals + $saldo;
  $acu = $subtotalg - $subtotalu;
  $total = number_format($total,2,'.',',');
  $i = number_format($i,2,'.',',');
  $ea = number_format($ea,2,'.',',');
  $saldo = number_format($saldo,2,'.',',');
  $width = 18;
  $pdf->Cell($width,6,$fecha,1,0,C);
  $width = 100;
  $pdf->Cell($width,6,getSubString(utf8_decode($des),54),1,0,L);
  $x = $pdf->GetX();
  $width = 18;
  $pdf->Cell($width,6,'$ '.$total,1,0,C);
  $width = 18;
  $pdf->Cell($width,6,'$ '.$i,1,0,C);
  $width = 18;
  $pdf->Cell($width,6,'$ '.$saldo,1,0,C);
  $width = 18;
  $pdf->Cell($width,6,'$ '.$ea,1,0,C);
  $pdf->Ln(6);
}

$tota = $subtotalg - $subtotalu;
  $subtotalg = number_format($subtotalg,2,'.',',');
  $subtotalu = number_format($subtotalu,2,'.',',');
  $subtotalt = number_format($subtotalt,2,'.',',');
  $subtotals = number_format($subtotals,2,'.',',');
  
  $totf = number_format($tota,2,'.',',');
$pdf->Ln(10);
$pdf->Cell(118, 8, '', 1,0,C);
$pdf->Cell(18, 8,'$ '.$subtotalt, 1,0,C);
$pdf->Cell(18, 8, '$ '.$subtotalg, 1,0,C);
$pdf->Cell(18, 8, '$ '.$subtotals, 1,0,C);
$pdf->Cell(18, 8, '$ '.$subtotalu, 1,0,C);
/*
if($contador >0){
      
    do{
      


      echo '
      <tr class="'.$id.'">
      <td class="'.$id.'"><input type="checkbox" id="'.$id.'" value="'.$id.'" name="cons[]" onclick="check(this,'.$id.');"></td>          
      <td class="'.$id.'">'.$fecha.'</td>
      <td class="'.$id.'">'.$des.'</td>
      <td class="'.$id.'"></td>
      <td class="'.$id.'">$'.$total.'</td>
      <td class="'.$id.'">$'.$i.'</td>
      <td class="'.$id.'">$'.$saldo.'</td>
      <td class="'.$id.'">$'.$ea.'</td>


      ';      
      if($tipo == 1){
        echo '      <td class="'.$id.'"><a href="formato.php?serie='.$s.'&folio='.$f.'" target="_blank"><img src="imagenes/impr.png"></a></td>';

      }         

      
      }while(($d = mysqli_fetch_array($registro)));
    }else{
      echo '<tr>
          <td colspan="10">No se encontraron resultados</td>
        </tr>';
      }
  $tota = $subtotalg - $subtotalu;
  $subtotalg = number_format($subtotalg,2,'.',',');
  $subtotalu = number_format($subtotalu,2,'.',',');
  $subtotalt = number_format($subtotalt,2,'.',',');
  $subtotals = number_format($subtotals,2,'.',',');
  
  $totf = number_format($tota,2,'.',',');
  echo '
      <tr>
      <td colspan="6"></br></td>
      </tr>
      <tr>
        <td colspan="4"></td>
        <td>$'.$subtotalt.'</td>
        <td>$'.$subtotalg.'</td>
        <td>$'.$subtotals.'</td>
        <td>$'.$subtotalu.'</td>
        <td>$'.$totf.'</td>
      </tr>';
  /*echo '<tr>
        <td colspan="3"></td>
        <td>Accion: </td>
        <td><select id="accnor">
          <option value="0" selected>Selecciona una opcion</option> 
          <option value="1">Revisado</option>
          <option value="2">No revisado</option>
         </td>
        <td colspan="1" ><button id="aplicaracc" onclick="revisado()" >Aceptar</button></td>
        
      </tr>';
  echo '</tbody></table></div>';
*/



$pdf->Output('ARQUEO DIA '.$desde.'.pdf','I');

?>