<?php require_once('../Connections/cn_conexion.php'); ?>
<?php  mysql_query("SET NAMES 'utf8'"); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

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

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

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO cuentas (nom_cuenta, tipo_cuenta, hab_cuenta) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['nom_cuenta'], "text"),
                       GetSQLValueString($_POST['tipo'], "int"),
                       GetSQLValueString($_POST['habilitado'], "text"));

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

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

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
	$updateSQL = "UPDATE gastos SET  tipo_cuenta=".$_POST['tipo'].", monto_real=".$_POST['tipo']."*monto WHERE id_cuenta='".$_POST['id_cuenta']."'";

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

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
  $updateSQL = sprintf("UPDATE cuentas SET nom_cuenta=%s, tipo_cuenta=%s, hab_cuenta=%s WHERE id_cuenta=%s",
                       GetSQLValueString($_POST['nom_cuenta'], "text"),
                       GetSQLValueString($_POST['tipo'], "int"),
                       GetSQLValueString($_POST['habilitado'], "text"),
                       GetSQLValueString($_POST['id_cuenta'], "int"));

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

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

$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_cuentas = "SELECT * FROM cuentas 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);
?>
<!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>
</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="clientes_lista" class="flotante_izq">
    	  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	    <tr>
    	      <strong>
    	      <td colspan="3">Lista de Cuentas</td></strong>
   	        </tr>
    	    <tr>
    	      <td colspan="3"><input name="buscar_cuenta" type="text" class="fn_text" id="buscar_cuenta" size="80" onkeypress="buscar_cuenta()"/></td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
    	    <tr>
    	      <td colspan="3">
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="68%" height="25" bgcolor="#110167"><p class="texto_normal">Cuentas</p></td>
                  <td width="17%" bgcolor="#110167"><p class="texto_normal">Tipo</p></td>
                  <td width="15%" bgcolor="#110167"><p>&nbsp;</p></td>
                </tr>
              </table>
              <?php
              if($totalRows_rs_cuentas>0){
			  ?>
              <div id="cont_listcuenta">
              <?php do { ?>
    	          <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	            <tr>
    	              <td width="5%" height="25">
                      <?php $ico_cuenta=$row_rs_cuentas['hab_cuenta'];?>
                      <img src="../imagenes/ico_cliente_<?php echo($ico_cuenta);?>.jpg" width="20" height="20" border="0" /></td>
    	              <td width="65%"><?php echo $row_rs_cuentas['nom_cuenta']; ?></td>
    	              <td width="15%">
					  <?php $ruc=$row_rs_cuentas['tipo_cuenta']; 
					  		if($ruc=="1"){
								$tipocuenta="Ingreso";
								}else{
									$tipocuenta="Egreso";
									}
							echo $tipocuenta; ?></td>
    	              <td width="15%"><p>| <a href="#" class="enlace_normal" onclick="modificar_cuenta('<?php echo $row_rs_cuentas['id_cuenta']; ?>')">Modificar</a> |</p></td>
   	                </tr>
   	              </table>
    	          <?php } while ($row_rs_cuentas = mysql_fetch_assoc($rs_cuentas)); ?>
              </div>
              <?php
			  }else{
				  echo("No hay documentos encontrados");
				  }
			  ?>
              </td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
  	    </table>
    	</div>
        <div id="cuenta_man" class="flotante_izq">
          <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td height="30" colspan="3"><p class="rot_man">&nbsp;&nbsp;&nbsp;&nbsp;Nueva Cuenta</p></td>
              </tr>
              <tr>
                <td width="3%">&nbsp;</td>
                <td colspan="2"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Nombre de Cuenta</td>
                  </tr>
                  <tr>
                    <td><input name="nom_cuenta" type="text" class="fn_text" id="nom_cuenta" size="60" autofocus/></td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td width="58%"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Tipo de Cuenta</td>
                  </tr>
                  <tr>
                    <td><input name="tipo" type="radio" id="radio" value="1" checked="checked" />
                      Ingreso&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;
                      <input type="radio" name="tipo" id="radio2" value="-1" />
                      Egreso </td>
                  </tr>
                </table></td>
                <td width="39%"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Habilitado</td>
                  </tr>
                  <tr>
                    <td><input name="habilitado" type="radio" id="radio5" value="1" checked="checked" />
                      Si&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;
                      <input type="radio" name="habilitado" id="radio6" value="0" />
                      No </td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30">&nbsp;</td>
                <td><input type="submit" name="button2" id="button2" value="Guardar" /></td>
              </tr>
            </table>
            <input type="hidden" name="MM_insert" value="form1" />
          </form>
        </div>
        <div class="limpiar"></div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_cuentas);
?>
