<?php require_once('../Connections/cn_conexion.php'); ?>
<?php include_once("../includes/funciones.php");?>
<?php  mysql_query("SET NAMES 'utf8'"); ?>
<?php
date_default_timezone_set('America/Lima');
$consulta="";
if(isset($_POST["f_dateini"])){
	$tipo_filtrado='1';
	$id_reporte="list_reportev";
	$f_dateini=fecha_peru($_POST["f_dateini"]);
	$f_datefin=fecha_peru($_POST["f_datefin"]);
	$tipo_boleta=$_POST["tipo_boleta"];
	$consulta.="SELECT * FROM documento, clientes WHERE clientes.id_cliente=documento.id_cliente AND documento.tipo_documento='b' ";
	$filtro_fechainicio=$f_dateini;
	$filtro_fechafin=$f_datefin;
	
	switch($tipo_boleta){
		case "-1":
			if($f_dateini<=$f_datefin){
				$consulta.=" AND documento.fecha_emision>='".$f_dateini."' AND documento.fecha_emision<='".$f_datefin."'";
			}
			$consulta.=" ORDER BY documento.hab_documento DESC, documento.num_documento ASC";
			$checked='checked=\"checked\"';
			$checkeda="";
			$checkedc="";
			break;
		case "1":
			if($f_dateini<=$f_datefin){
				$consulta.=" AND documento.fecha_emision>='".$f_dateini."' AND documento.fecha_emision<='".$f_datefin."'";
			}
			$consulta.="AND documento.hab_documento='1' ORDER BY  documento.num_documento ASC";
			$checked='';
			$checkeda='checked=\"checked\"';
			$checkedc="";			
			break;
		case "0":
			if($f_dateini<=$f_datefin){
				$consulta.=" AND documento.fecha_cancelado>='".$f_dateini."' AND documento.fecha_cancelado<='".$f_datefin."'";
			}
			$consulta.="AND documento.hab_documento='0' ORDER BY  documento.num_documento ASC";		
			$checked="";
			$checkeda="";
			$checkedc='checked=\"checked\"';
			break;
		}
}else{
	$filtro_fechainicio=date("Y-m-d");
	$filtro_fechafin=date("Y-m-d");		
	$tipo_filtrado='0';
	$checked='checked=\"checked\"';
	$checkeda="";
	$checkedc="";
	$id_reporte="list_reportev";	
	$f_dateini=fecha_peru(date("d-m-Y"));	
	$f_datefin=fecha_peru(date("d-m-Y"));	
	$consulta.="SELECT * FROM documento, clientes WHERE clientes.id_cliente=documento.id_cliente  AND documento.fecha_emision>='".date('Y-m-d')."' AND documento.fecha_emision<='".date('Y-m-d')."'  AND documento.tipo_documento='b'  ORDER BY documento.hab_documento DESC,  documento.num_documento ASC";
	}



?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}
$_SESSION["modulo"]="REPORTE DE BOLETAS POR FECHA";
$modulo=$_SESSION["modulo"];
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "../index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "../index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$colname_rs_usuario = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_rs_usuario = $_SESSION['MM_Username'];
}
mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_usuario = sprintf("SELECT * FROM usuarios WHERE dni_usuario = %s", GetSQLValueString($colname_rs_usuario, "text"));
$rs_usuario = mysql_query($query_rs_usuario, $cn_conexion) or die(mysql_error());
$row_rs_usuario = mysql_fetch_assoc($rs_usuario);
$totalRows_rs_usuario = mysql_num_rows($rs_usuario);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_docreporte = "".$consulta."";
$rs_docreporte = mysql_query($query_rs_docreporte, $cn_conexion) or die(mysql_error());
$row_rs_docreporte = mysql_fetch_assoc($rs_docreporte);
$totalRows_rs_docreporte = mysql_num_rows($rs_docreporte);

//echo($query_rs_docreporte);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SISTEMA DE FACTURACION</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript" src="../js/funciones.js"></script>
<script src="../src/js/jscal2.js"></script>
<script src="../src/js/lang/es.js"></script>
<link rel="stylesheet" type="text/css" href="../src/css/jscal2.css" />
<link rel="stylesheet" type="text/css" href="../src/css/border-radius.css" />
<link rel="stylesheet" type="text/css" href="../src/css/win2k/win2k.css" />
</head>

<body>
<?php include_once("../includes/cabecera.php");?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
    <div id="contenedor" onmouseout="cerrar_menu()">
    	<div id="reporte_gasto">
    	  <form id="form1" name="form1" method="post" action="">
    	    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	      <tr>
    	        <td width="11%">Seleccione Filtro</td>
    	        <td width="14%">&nbsp;</td>
    	        <td width="7%">&nbsp;</td>
    	        <td width="14%">&nbsp;</td>
    	        <td width="9%">&nbsp;</td>
    	        <td width="26%">&nbsp;</td>
    	        <td width="19%">&nbsp;</td>
  	        </tr>
    	      <tr>
    	        <td>Fecha Inicio</td>
    	        <td><input name="f_dateini" id="f_dateini" size="15" readonly="readonly" value="<?php echo(fecha_peru($f_dateini))?>"/><button id="f_btnini">...</button>
				  <script type="text/javascript">//<![CDATA[
                      Calendar.setup({
						fdow: 0,
                        inputField : "f_dateini",
                        trigger    : "f_btnini",
                        onSelect   : function() { this.hide() },
                        showTime   : 12,
                        dateFormat : "%d-%m-%Y"
                      });
                    //]]></script>
                </td>
    	        <td>Fecha Fin</td>
    	        <td><input name="f_datefin" id="f_datefin" size="15" readonly="readonly" value="<?php echo(fecha_peru($f_datefin))?>"/><button id="f_btnfin">...</button>
					<script type="text/javascript">//<![CDATA[
                      Calendar.setup({
						fdow: 0,
                        inputField : "f_datefin",
                        trigger    : "f_btnfin",
                        onSelect   : function() { this.hide() },
                        showTime   : 12,
                        dateFormat : "%d-%m-%Y"
                      });
                    //]]></script>
                </td>
    	        <td>Tipo de Boleta</td>
    	        <td><input name="tipo_boleta" type="radio" id="radio3" value="-1" <?php echo($checked);?> />
    	          Emitidas &nbsp;
                  <input type="radio" name="tipo_boleta" id="radio" value="1" <?php echo($checkeda);?>/> 
                  Pendientes
&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="tipo_boleta" id="radio2" value="0" <?php echo($checkedc);?>/> 
Canceladas
</td>
    	        <td><input type="submit" name="button" id="button" value="Filtrar" />
   	            <input name="tipo_filtrado" type="hidden" id="tipo_filtrado" value="<?php echo($tipo_filtrado);?>" /></td>
  	        </tr>
  	      </table>
            </form>
          <div >
          <?php 
		  if($totalRows_rs_docreporte>0){
		  ?>
            <form id="form2" name="form2" method="post" action="reportedoc_excel.php">
              <table width="98%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
                <tr>
                  <td width="1%" align="center" bgcolor="#000066"><p class="texto_normal">CANCELACIÓN</p></td>
                  <td width="7%" bgcolor="#000066" align="center"><p class="texto_normal">BOLETA</p></td>
                  <td width="30%" bgcolor="#000066"><p class="texto_normal">CLIENTE</p></td>
                  <td width="7%" bgcolor="#000066" align="center"><p class="texto_normal">MONTO<BR /> EN S/</p></td>
                  <td width="12%" bgcolor="#000066" align="center"><p class="texto_normal">TOTAL<BR /> EN S/</p></td>
                  <td width="11%" bgcolor="#000066" align="center"><p class="texto_normal">TOTAL<BR /> EN $.</p></td>
                  <td width="11%" bgcolor="#000066" align="center"><span class="texto_normal">EMISIÓN</span></td>
                </tr>
                
                <tr>
                  <td height="20" colspan="7" align="center" >
                  <div id="cont_listdoc">
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <?php $i=1;?>
                <?php do { ?>
                <?php 
				$res=$i%2;
				if($res==0){
					$color="#CDEBFC";
					}else{
						$color="#ffffff";
						}
				$monto=$row_rs_docreporte['monto'];
				$moneda=$row_rs_docreporte['moneda'];
				$tipocambio=$row_rs_docreporte['tipo_cambio'];
				$montodolares=montodolares($monto,$moneda,$tipocambio);
				$montosoles=round(montosoles($monto,$moneda,$tipocambio),2);
/*				$total=$montosoles;
				$montoaux=$montosoles;
				$montosoles=round(($montosoles*100)/118,2);
				$igv=$montoaux-$montosoles;*/

				$igv=round(($montosoles*$row_rs_docreporte['igv'])/100,2);
				$totals=round($montosoles+$igv,2);
				$totald=round(montodolares($totals,$moneda,$tipocambio));
				
				if($row_rs_docreporte['hab_documento']=='0'){
				$classe_colortexto="enlace_cancelar";
					$clase_texto='class="texto_cancelar"';
					}else{
						$classe_colortexto="enlace_normal";
						$clase_texto="";
						}
				?>
                      <tr>
                        <td width="6%" height="20" align="center" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>>
                    <?php $fechfin=$row_rs_docreporte['fecha_cancelado']; echo fecha_peru($fechfin); ?>
                  </p></td>
                        <td width="10%" align="center" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>>
                    <?php $numdoc=$row_rs_docreporte['num_documento']; echo $numdoc; ?>
                  </p></td>
                        <td width="35%" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>>
                    <?php $nomcli=$row_rs_docreporte['nom_cliente']; echo $nomcli; ?>
                  </p></td>
                        <td width="10%" align="right" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>><?php echo number_format(decimals($montosoles),2); ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p></td>
                        <td width="13%" align="right" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>>
                    <?php  echo number_format(decimals($totals),2);?>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p></td>
                        <td width="13%" align="right" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>><?php echo number_format(decimals($totald),2);?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p></td>
                        <td width="13%" align="center" style="background-color:<?php echo($color);?>"><p <?php echo($clase_texto);?>>
                    <?php $fechemi=$row_rs_docreporte['fecha_emision']; echo fecha_peru($fechemi); ?>
                  </p></td>
                      </tr>
                <?php $i++;?>
                <?php } while ($row_rs_docreporte = mysql_fetch_assoc($rs_docreporte)); ?>
                    </table>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td><input name="inicio" type="hidden" id="inicio2" value="<?php echo($filtro_fechainicio)?>" />
                  <input name="fin" type="hidden" id="fin" value="<?php echo($filtro_fechafin);?>" /></td>
                  <td><input name="reporte_titulo" type="hidden" id="reporte_titulo" value="Reporte de Boletas" /></td>
                  <td><input name="consulta" type="hidden" id="consulta" value="<?php echo($consulta);?>" /><input name="doc" type="hidden" id="doc" value="b" /></td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td><input type="submit" name="button2" id="button2" value="Exportar Excel" /></td>
                </tr>
              </table>
            </form>
            <?php
		  }else{
			  echo("<p>&nbsp;</p><br>");
			  echo("No hay datos para esta consulta");
			  }
			?>
          </div>
        </div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_docreporte);
?>
