<?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'");
?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

$_SESSION["modulo"]="GASTOS";
if($_SESSION["tipo_sesion"]!="1"){
	header("location:../".$_SESSION["ruta_permitida"]);
	}
$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;
}
}

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;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
	$fechaini=fecha_peru($_POST["f_dateini"]);
	switch($_POST['moneda']){
	case 'S':
		$monto_gasto=$_POST['monto'];
		break;
	case 'D':
		$monto_gasto=round($_POST['monto']*$_POST['tipo_cambio'],2);
		break;
	}
}



if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO gastos (id_cliente, id_cuenta, fecha, descripcion, monto, monto_real, moneda, tipo_cuenta, tipo_cambio) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['idcliente'], "int"),
                       GetSQLValueString($_POST['id_cuenta'], "int"),
                       GetSQLValueString($fechaini, "date"),
                       GetSQLValueString($_POST['descripcion'], "text"),
                       GetSQLValueString($monto_gasto, "double"),
					   GetSQLValueString($monto_gasto*$_POST['tipocuenta'], "double"),
                       GetSQLValueString("S", "text"),
                       GetSQLValueString($_POST['tipocuenta'], "text"),
                       GetSQLValueString($_POST['tipo_cambio'], "double"));

  mysql_select_db($database_cn_conexion, $cn_conexion);
  $Result1 = mysql_query($insertSQL, $cn_conexion) or die(mysql_error());

  $insertGoTo = "nuevo_gastos.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}


$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_gastos = "SELECT * FROM gastos, cuentas WHERE cuentas.id_cuenta=gastos.id_cuenta AND gastos.hab_gasto='1' ORDER BY gastos.id_gasto DESC";
$rs_gastos = mysql_query($query_rs_gastos, $cn_conexion) or die(mysql_error());
$row_rs_gastos = mysql_fetch_assoc($rs_gastos);
$totalRows_rs_gastos = mysql_num_rows($rs_gastos);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cliente = "SELECT * FROM clientes WHERE clientes.hab_cliente='1' ORDER BY clientes.nom_cliente ASC";
$rs_cliente = mysql_query($query_rs_cliente, $cn_conexion) or die(mysql_error());
$row_rs_cliente = mysql_fetch_assoc($rs_cliente);
$totalRows_rs_cliente = mysql_num_rows($rs_cliente);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cuentas = "SELECT * FROM cuentas WHERE cuentas.hab_cuenta='1' ORDER BY cuentas.nom_cuenta ASC";
$rs_cuentas = mysql_query($query_rs_cuentas, $cn_conexion) or die(mysql_error());
$row_rs_cuentas = mysql_fetch_assoc($rs_cuentas);
$totalRows_rs_cuentas = mysql_num_rows($rs_cuentas);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cajagastos = "SELECT * FROM caja_gastos";
$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);

$compra=$_SESSION["compra"];
$venta=$_SESSION["venta"];
$igv=$_SESSION["igv"];
$_SESSION["numcajas"]=$totalRows_rs_cajagastos;
$num_cajas=$_SESSION["numcajas"];		  
?>
<!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 onload="foco_texto()">
<?php include_once("../includes/cabecera.php");?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
    <div id="contenedor_nuevo" onmouseout="cerrar_menu()">
    <div id="cont_nuevo">
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><p class="rot_man">&nbsp;&nbsp;&nbsp;&nbsp;Nuevo Gasto</p></td>
        </tr>
        <tr>
          <td height="10"></td>
        </tr>
        <tr>
          <td bgcolor="#FFFFFF"><form id="form1" name="form1" method="post" action="">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="3%" height="10"></td>
                <td width="42%"></td>
                <td width="55%"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Fecha</p></td>
                        </tr>
                      <tr>
                        <td><input name="f_dateini" class="fn_textnuevo" id="f_dateini" value="<?php echo(date("d-m-Y"))?>" size="15" onfocus="limpiar_fecha(this.value,'f_dateini')"   onblur="analizar_fecha(this.value,'f_dateini')" onkeyup="valid_fecha(this.value,'f_dateini')" />
                          <input type="button" name="f_btnini" id="f_btnini" value="..." />
                          <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>
                        </tr>
                      </table></td>
                    <td width="50%"><div id="numerocaja"></div></td>
                    </tr>
                  </table></td>
                <td height="300" rowspan="5" valign="top">
                <div id="cont_cuenta" style="display:none">
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td height="10"></td>
                    </tr>
                    <tr>
                      <td bgcolor="#FFFFFF"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td>&nbsp;</td>
                        </tr>
                        <tr>
                          <td><div id="listado_cuentas" class="cont_list">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                              <?php do { ?>
                                <tr>
                                  <td width="2%" height="20" align="center">&nbsp;</td>
                                  <td width="95%"><p class="enlace_normalgrande"><a href="#" class="enlace_normalgrande" onclick="selec_cuenta('<?php echo $row_rs_cuentas['nom_cuenta']; ?>@@<?php echo $row_rs_cuentas['id_cuenta']; ?>@@<?php echo $row_rs_cuentas['tipo_cuenta']; ?>')"><?php echo $row_rs_cuentas['nom_cuenta']; ?></a> </p>
                                    <hr />
                                    </p></td>
                                  <td width="4%">&nbsp;</td>
                                  </tr>
                                <?php } while ($row_rs_cuentas = mysql_fetch_assoc($rs_cuentas)); ?>
                              <tr>
                                <td align="center">&nbsp;</td>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                                </tr>
                              </table>
                            </div></td>
                        </tr>
                        <tr>
                          <td>&nbsp;</td>
                        </tr>
                      </table></td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                  </table>
                </div>
                <div id="cont_buscar" style="display:none">
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                    <tr>
                      <td bgcolor="#FFFFFF"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td>&nbsp;</td>
                          </tr>
                        <tr>
                          <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                          </tr>
                        <tr>
                          <td><div id="listado_clientes" class="cont_list">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                              <?php do { ?>
                                <tr>
                                  <td width="2%" height="20" align="center">&nbsp;</td>
                                  <td width="95%"><p class="enlace_normalgrande"><a href="#" class="enlace_normalgrande" onclick="selec_cliente('<?php echo ($row_rs_cliente['nom_cliente']); ?>@@<?php echo($row_rs_cliente['id_cliente']);?>')"><?php echo $row_rs_cliente['nom_cliente']; ?></a></p>
                                    <hr />
                                    </p></td>
                                  <td width="4%">&nbsp;</td>
                                  </tr>
                                <?php } while ($row_rs_cliente = mysql_fetch_assoc($rs_cliente)); ?>
                              <tr>
                                <td align="center">&nbsp;</td>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                                </tr>
                              </table>
                            </div></td>
                          </tr>
                        </table></td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                  </table>
                </div>
                
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><p class="estilo_letranuevo">Cliente</p></td>
                    </tr>
                  <tr>
                    <td><input name="cliente" type="text" class="fn_textnuevo" id="cliente" size="55" onkeypress="busquedacli()" autofocus />
                      <input type="button" name="button2" id="button1" value="..." onclick="buscarcli('1')"/>
                      <input name="idcliente" type="hidden" id="idcliente" />
                      <input type="hidden" name="idcli" id="idcli" />
                      <input name="activo" type="hidden" id="activo" value="0" /></td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><p><span class="estilo_letranuevo">Cuenta</span>
                      <input type="hidden" name="tipo_cuenta" id="tipo_cuenta" />
                      </p></td>
                    </tr>
                  <tr>
                    <td><input name="cuenta" type="text" class="fn_textnuevo" id="cuenta" size="55" onkeypress="busquedacuenta()" onblur="next_focus('monto')"/>
                      <input type="button" name="button4" id="button3" value="..." onclick="buscarcuenta('4')"/>
                      <input name="id_cuenta" type="hidden" id="id_cuenta" />
                      <input type="hidden" name="tipocuenta" id="tipocuenta" />
                      <input type="hidden" name="idcuenta" id="idcuenta" /></td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td><input name="descripcion" type="hidden" class="fn_text" id="descripcion" value="0" size="70" /></td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Monto</p></td>
                        </tr>
                      <tr>
                        <td><input name="monto" type="text" class="fn_textnuevo" id="monto" size="10" /></td>
                        </tr>
                      </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Moneda</p></td>
                        </tr>
                      <tr>
                        <td><select name="moneda" class="fn_textnuevo" id="moneda">
                          <option value="S">Soles</option>
                          <option value="D">Dolares</option>
                          </select></td>
                        </tr>
                      </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Tipo de Cambio</p></td>
                        </tr>
                      <tr>
                        <td><input name="tipo_cambio" type="text" class="fn_textnuevo" id="tipo_cambio" value="<?php echo($compra);?>" size="10" /></td>
                        </tr>
                      </table></td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td><input name="MM_insert" type="hidden" id="MM_insert" value="form1" /></td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td width="78%">&nbsp;</td>
                    <td width="22%"><input type="submit" name="button2" id="button2" value="Guardar" /></td>
                    </tr>
                  </table></td>
              </tr>
              </table>
          </form></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
        </tr>
      </table>
    </div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_cliente);

mysql_free_result($rs_cuentas);

mysql_free_result($rs_cajagastos);
?>
