<?php require_once('../Connections/cn_conexion.php'); ?>
<?php include_once('../includes/funciones.php');?>
<?php
date_default_timezone_set('America/Lima');
mysql_query("SET NAMES 'utf8'");
$consulta="";
if(isset($_POST["f_dateini"])){
	$act_filtro=1;
	$tipo_filtrado='-1';
	$id_reporte="list_reportev";
	$f_dateini=fecha_peru($_POST["f_dateini"]);
	$f_datefin=fecha_peru($_POST["f_datefin"]);
	$tipo_caja=$_POST["tipo_caja"];
	$consulta.="SELECT *, SUM(gastos.monto_real) FROM caja_gastos, gastos, clientes WHERE caja_gastos.id_cliente=gastos.id_cliente AND gastos.num_caja=caja_gastos.num_caja AND clientes.id_cliente=caja_gastos.id_cliente AND clientes.id_cliente=gastos.id_cliente ";
	$filtro_fechainicio=$f_dateini;
	$filtro_fechafin=$f_datefin;
	if($f_dateini<=$f_datefin){
		$consulta.="AND caja_gastos.fecha_inicio>='".$f_dateini."' AND  caja_gastos.fecha_inicio<='".$f_datefin."' ";
		}
	switch($tipo_caja){
		case "1":
			$consulta.="AND caja_gastos.hab_cajagasto='0' GROUP BY  gastos.num_caja";
			$checked='';
			$checkeda='checked=\"checked\"';
			$checkedc="";			
			break;
		case "-1":
			$consulta.="AND caja_gastos.hab_cajagasto='1' GROUP BY  gastos.num_caja ORDER BY caja_gastos.num_caja DESC ";		
			$checked="";
			$checkeda="";
			$checkedc='checked=\"checked\"';
			break;
		}
}else{
	$act_filtro=0;
	$filtro_fechainicio=date("Y-m-d");
	$filtro_fechafin=date("Y-m-d");	
	$tipo_filtrado='-1';
	$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 *, SUM(gastos.monto_real) FROM caja_gastos, gastos, clientes WHERE caja_gastos.id_cliente=gastos.id_cliente AND gastos.num_caja=caja_gastos.num_caja  AND caja_gastos.fecha_inicio>='".$f_dateini."' AND  caja_gastos.fecha_inicio<='".$f_datefin."' AND clientes.id_cliente=caja_gastos.id_cliente AND clientes.id_cliente=gastos.id_cliente GROUP BY  gastos.num_caja  ORDER BY caja_gastos.hab_cajagasto DESC";
	$consulta="SELECT *, SUM(gastos.monto_real) FROM caja_gastos, gastos, clientes WHERE caja_gastos.id_cliente=gastos.id_cliente AND gastos.num_caja=caja_gastos.num_caja AND clientes.id_cliente=caja_gastos.id_cliente AND clientes.id_cliente=gastos.id_cliente GROUP BY gastos.num_caja ORDER BY caja_gastos.num_caja DESC";
	}

?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

$_SESSION["modulo"]="REPORTE DE GASTOS 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_cajareporte = "".$consulta."";
$rs_cajareporte = mysql_query($query_rs_cajareporte, $cn_conexion) or die(mysql_error());
$row_rs_cajareporte = mysql_fetch_assoc($rs_cajareporte);
$totalRows_rs_cajareporte = mysql_num_rows($rs_cajareporte);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cajagastos = "".$consulta."";
$rs_cajagastos = mysql_query($query_rs_cajagastos, $cn_conexion) or die(mysql_error());
$row_rs_cajagastos = mysql_fetch_assoc($rs_cajagastos);
$totalRows_rs_cajagastos = mysql_num_rows($rs_cajagastos);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cajaabierta = "SELECT *, SUM(gastos.monto_real) FROM gastos, clientes WHERE clientes.id_cliente=gastos.id_cliente AND  gastos.hab_gasto='1' GROUP BY gastos.id_cliente   ORDER BY clientes.nom_cliente ASC";
$rs_cajaabierta = mysql_query($query_rs_cajaabierta, $cn_conexion) or die(mysql_error());
$row_rs_cajaabierta = mysql_fetch_assoc($rs_cajaabierta);
$totalRows_rs_cajaabierta = mysql_num_rows($rs_cajaabierta);
?>
<!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 align="right">
    <div id="contenedor" onmouseout="cerrar_menu()">
    	<div id="reporte_gasto">
        	<div id="filtro">
        	  <form id="form1" name="form1" method="post" action="">
        	    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        	      <tr>
        	        <td width="7%">&nbsp;</td>
        	        <td width="11%">&nbsp;</td>
        	        <td width="22%">&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
      	        </tr>
        	      <tr>
        	        <td colspan="6">&nbsp;&nbsp;Seleccione Filtro</td>
      	        </tr>
        	      <tr>
        	        <td colspan="3">&nbsp;&nbsp;<input name="clientes" type="text" id="clientes" size="60" onkeypress="busqueda_caja(this.value)" placeholder="Introduzca Cliente"/></td>
        	        <td width="32%"><div id="fecha_filtro">
        	          <table width="100%" border="0" cellspacing="0" cellpadding="0">
        	            <tr>
        	              <td>Inicio&nbsp;
        	          <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>Fin&nbsp;
        	          <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>
      	              </tr>
      	            </table>
        	        </div></td>
        	        <td width="15%"><input name="tipo_caja" type="radio" id="radio5" value="1" <?php echo($checkeda);?> onchange="open_closed()"/>
        	          Abierta&nbsp;&nbsp;&nbsp;&nbsp;
        	          <input name="tipo_caja" type="radio" id="radio6" value="-1" checked="checked" <?php echo($checkedc);?> onchange="open_closed()"/>
        	          Cerrado</td>
        	        <td width="13%"><div id="boton_filtro"><input type="submit" name="button3" id="button3" value="Filtrar" /></div>
        	          <input name="tipo_filtrado" type="hidden" id="tipo_filtrado" value="<?php echo($tipo_filtrado);?>" /></td>
      	        </tr>
        	      <tr>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
        	        <td>&nbsp;</td>
      	        </tr>
      	      </table>
      	      </form>
       	  </div>
            <div id="caja_privada"></div>
            <div id="lista_gastostodos">
        	<div id="caja_abierta" class="caja">
            <?php
            if($totalRows_rs_cajaabierta>0){
			?>
        	  <table width="100%" border="0" cellspacing="0" cellpadding="0">
        	    <tr>
        	      <td width="76%" bgcolor="#000066" class="texto_normal">CLIENTE</td>
        	      <td width="24%" align="center" bgcolor="#000066" class="texto_normal">MONTO S/</td>
      	      </tr>
       	        <tr>
       	          <td colspan="2">
                  <div id="cont_listcli">
                  <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";
						}
				if($row_rs_cajagastos['hab_cajagasto']=='0'){
				$classe_colortexto="enlace_cancelar";
					$clase_texto='class="texto_cancelar"';
					}else{
						$classe_colortexto="enlace_normal";
						$clase_texto="";
						}
			?>                  
       	            <tr>
       	              <td width="75%" height="20" style="background-color:<?php echo($color);?>"><p><a href="#" class="<?php echo($classe_colortexto);?>" onclick="detallecajaopen('<?php echo $row_rs_cajaabierta['id_cliente']; ?>')"><?php echo $row_rs_cajaabierta['nom_cliente']; ?></a></p></td>
       	              <td width="25%" align="right" style="background-color:<?php echo($color);?>"><?php $montocaja= round($row_rs_cajaabierta['SUM(gastos.monto_real)'],2);  echo(number_format(decimals($montocaja),2)) ?>
       	                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
     	              </tr>
				  <?php $i++;?>
        	      <?php } while ($row_rs_cajaabierta = mysql_fetch_assoc($rs_cajaabierta)); ?>                     
     	            </table>
                    </div>
                  </td>
   	            </tr>
              </table>
            <?php
			}else{
				echo("<p>No hay cajas abiertas por el momento</p>");
				}
			?>
        	</div>
            <div id="caja_cerrada" class="caja">
            <?php if($totalRows_rs_cajagastos>0){?>
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="11%" bgcolor="#000066" class="texto_normal">CAJA</td>
                  <td width="48%" bgcolor="#000066" class="texto_normal">CLIENTE</td>
                  <td width="19%" align="center" bgcolor="#000066" class="texto_normal">MONTO S/</td>
                  <td width="22%" align="center" bgcolor="#000066" class="texto_normal">CIERRE</td>
                </tr>
                <tr>
                  <td colspan="4">
                  <div id="cont_listclic">
                  <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";
						}
				if($row_rs_cajagastos['hab_cajagasto']=='0'){
				$classe_colortexto="enlace_cancelar";
					$clase_texto='class="texto_cancelar"';
					}else{
						$classe_colortexto="enlace_normal";
						$clase_texto="";
						}
			?>                  
                    <tr>
                      <td width="11%" style="background-color:<?php echo($color);?>"><?php $cajagastosncaja=$row_rs_cajagastos['num_caja']; echo $cajagastosncaja ; ?></td>
                      <td width="48%" height="20" style="background-color:<?php echo($color);?>"><p><a href="#" class="<?php echo($classe_colortexto);?>" onclick="detallecaja('<?php echo $row_rs_cajagastos['num_caja']; ?>')"><?php $cajagastosncliente=$row_rs_cajagastos['nom_cliente']; echo $cajagastosncliente; ?></a></p></td>
                      <td width="19%" align="right" style="background-color:<?php echo($color);?>">
                      <?php
	                      $cajagastosmreal=round($row_rs_cajagastos['SUM(gastos.monto_real)'],2);
						  if($cajagastosmreal<0){
							  $estilo_texto="class='textocajamonto'";
							  }else{
								  $estilo_texto="";
								  }
					  ?>
                      <p <?php echo($estilo_texto);?>>
					  <?php 
					  	echo number_format(decimals(abs($cajagastosmreal)),2);
					  ?>
                        &nbsp;&nbsp;&nbsp;&nbsp;</p></td>
                      <td width="22%" align="center" style="background-color:<?php echo($color);?>"><?php $cajagastosfcierre=$row_rs_cajagastos['fecha_cierre']; echo fecha_peru($cajagastosfcierre); ?></td>
                    </tr>
              <?php $i++;?>
              <?php } while ($row_rs_cajagastos = mysql_fetch_assoc($rs_cajagastos)); ?>
                  </table> 
                  </div>
                  <p>&nbsp;</p></td>
                  </tr>
                  
              </table>
              <?php }else{
				  echo("<p>No hay cajas cerradas por el momento</p>");
				  }?>
              <form id="form2" name="form2" method="post" action="reportegastosc_excel.php">
                <input name="act_filtro" type="hidden" id="act_filtro" value="<?php echo($act_filtro);?>" />
                <input name="f_datefin" type="hidden" id="f_datefin" value="<?php echo(fecha_peru($f_datefin));?>" />
                <input name="f_dateini" type="hidden" id="f_dateini" value="<?php echo(fecha_peru($f_dateini));?>" />
<input name="consulta_gastos" type="hidden" id="consulta_gastos" value="<?php echo($query_rs_cajagastos);?>" />
                <input type="submit" name="button" id="button" value="Exportar Cuentas Cerrados" />
              </form>
            </div>
          <div class="limpiar"></div>
          </div>
        </div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_cajareporte);

mysql_free_result($rs_cajagastos);

mysql_free_result($rs_cajaabierta);
?>
