<?php
 /*-----------------------------------*
  * Proyecto : SAI                    *
  * Autor    : Federico A. Ocampo     *
  * Desc: Interfaz web de Seleccion   *
  *       para Armado de Informes     *
  *-----------------------------------*/

  //--------------------------------------
  require_once "AppConfig.php";
  //--------------------------------------

  //-------------------------- FUNCIONES AUXILIARES VARIAS ------------------------------

  /** Funcion: armarOpcionesSelect
  *   Recibe un arreglo asociativo bidimensional de tipo arreglo[n][codigo][descripcion]
  *   Crea el esquema de opciones HTML <option value="codigo" selected="?">codigo] - descripcion</option>
  *   El parametro $elegido indica que opcion es la seleccionada 
  */
  function armarOpcionesSelect(&$appConfig, &$aDatos, $elegido, $descr)
  {
    $NIVEL_DEBUG = $appConfig->DEBUG["nivel"]; //Para manejar errores
    $ret_sel = ""; //retorno de la funcion

    //Precondicion: El arreglo no puede estar vacio
    $longDatos = sizeof($aDatos);
    
    if($longDatos == 1 )
    {
    	$campoId   = key($aDatos[0]);
    	if($aDatos[0][$campoId] == '' )
    	{
    		return $ret_sel;
    	}
    	reset($aDatos[0]);
    }
    
    if($longDatos > 0)
    {
      $tagOption = ""; //String para almacenar el codigo HTML de cada opcion de select

      //Como el arreglo es asociativo y no conocemos los nombres, los tomamos del primer elemento
      $campoId   = key($aDatos[0]);
      next($aDatos[0]); //avanza el puntero interno del arreglo pos[0] = (Id,Descripcion)
      $campoDesc = key($aDatos[0]);

      if(isset($descr))
      {
          next($aDatos[0]); //avanza el puntero interno del arreglo pos[0] = (Id,Descripcion)
          $campoDesc2 = key($aDatos[0]);
      }
	  
      for($i=0;$i<$longDatos;$i++)
      {
        $tagOption = "<option value=\"{$aDatos[$i][$campoId]}\"";
        //Si el elemento actual es el elegido en el select, se agrega el codigo HTML para marcarlo 'selected'
        if( isset($elegido) 
        	&& $elegido == $aDatos[$i][$campoId] )
        {
          $tagOption .= " selected style=\"font-weight: bold;\" ";
        }
        //El texto de la opcion es Id-Descripcion
        $tagOption .= ">{$aDatos[$i][$campoId]}] - {$aDatos[$i][$campoDesc]} {$aDatos[$i][$campoDesc2]} </option>\n";

        $ret_sel .= $tagOption;
      }
      reset($aDatos[0]);
    }
    else
    {
      if($NIVEL_DEBUG > 1)
      {
        $war_msg = "Error en parametros: ${$longDatos}";
        trigger_error($war_msg, E_USER_WARNING);
      }
    }

    return $ret_sel;
  }


  /** Genera el codigo JavaScript de dos arreglos de fechas 'fdes' y 'fhas' a partir de un arreglo de la
  * forma arreglo[codigo][descripcion][fechaDesde][fechaHasta]*/
  function armarArrayFechasDeVersion(&$aVersiones)
  {
    //PRECONDICION: el arreglo tiene al menos un elemento

    $ret_afv = ""; //retorno de la funcion
    $sizeArray = sizeof($aVersiones); //tamanio del arreglo

    if($sizeArray > 0)
    {
      $ret_afv .= "var aFechasDesde = new Array($sizeArray);\n".
                  "var aFechasHasta = new Array($sizeArray);\n";

      for($i=0;$i<$sizeArray;$i++)
      {
        //crea el codigo javascript de los dos arreglos
        $ret_afv .= "aFechasDesde[$i] = \"{$aVersiones[$i]["mov_fdes"]}\";\n".
                    "aFechasHasta[$i] = \"{$aVersiones[$i]["mov_fhas"]}\";\n";
      }
    }
    else
    {
      $err_msg = "Error en parametros de funcion armarArrayFechasDeVersion: parametro nulo";
      trigger_error($err_msg, E_USER_ERROR);
    }

    return $ret_afv;
  }

  //Devuelve la fecha actual en el formato seteado
  function verFechaActual($formato)
  {
    $ret_fecha = strftime($formato, time());
    return $ret_fecha;
  }
 
	/**
	* Utility function to return a value from a named array or a specified default
	* Codigo obtenido del soft Mambo Open Source (www.mamboserver.com)
	* @copyright (C) 2000 - 2004 Miro International Pty Ltd
	* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
	*
	* @param array  arreglo con los valores (POST, GET, etc) a recibir
	* @param string nombre del parametro
	* @param T      valor por defecto si no existe el dato
	* @param int    mascara a utilizar
	*
	* @return T
	*/
	define('_CIG_NOTRIM'   , 0x0001 );
	define('_CIG_ALLOWHTML', 0x0002 );
	define('_CIG_NOSLASHES', 0x0003 );
	define('_CIG_SQLSLASHES',0x0004 );
	function utl_getParam( &$arr, $name, $def=null, $mask=0 )
	{
		$return = null;
		if (isset( $arr[$name] ))
		{
			if (is_string( $arr[$name] ))
			{
				/* Elimina los espacios */
				if (!($mask & _CIG_NOTRIM)) {
					$arr[$name] = trim( $arr[$name] );
				}
				/* Elimina los tags html */
				if (!($mask & _CIG_ALLOWHTML)) {
					$arr[$name] = strip_tags( $arr[$name] );
				}
				/* Elimina las contrabarras */
				if ($mask & _CIG_NOSLASHES)
				{
					if (get_magic_quotes_gpc()) {
						$arr[$name] = stripslashes($arr[$name]);
					}
				}
				elseif ($mask & _CIG_SQLSLASHES)
					{
						// Stripslashes
						if (get_magic_quotes_gpc()) {
							$arr[$name] = stripslashes($arr[$name]);
						}
						// Quote if not integer
						if (!is_numeric($arr[$name])) {
							if (function_exists('mysql_real_escape_string')) {
								$arr[$name] = @mysql_real_escape_string($arr[$name]);
							} else {
								$arr[$name] = @mysql_escape_string($arr[$name]);
							}
						}
					}
					else
					{
						//Por defecto escapa los caracteres sin importar las Magic Quotes
						if (get_magic_quotes_gpc()) {
							$arr[$name] = stripslashes($arr[$name]);
						}
						$arr[$name] = addslashes($arr[$name]);
					}
			}
			return $arr[$name];
		}
		else
		{
			return $def;
		}
	}

	/**
	* Prints the page header.
	* @param $title The title of the page
	* @param $css css tag
	* @param $script script tag
	*/
	function utl_printHeader($title = '', $css = null, $script = null) {
		global $appConfig;
	
		echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-Transitional.dtd\">\n";
		echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"es\" lang=\"es\">\n";
		echo "<head>\n";
		echo '<title>', htmlspecialchars($appConfig['app']['name']);
		if ($title != '') {
			echo " - {$title}";
		}
		echo "</title>\n";
		echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n";
		echo '<meta name="author" content="', htmlspecialchars($appConfig['app']['comp']),"\" />\n";
		echo '<meta name="description" content="', htmlspecialchars($appConfig['app']['desc']),"\" />\n";
		if ($css) {
			echo "{$css}\n";
		}
		if ($script) {
			echo "{$script}\n";
		}
		echo "</head>\n";
	}
	
	/**
	* Prints the page footer
	*/
	function utl_printFooter() {
		echo "</body>\n</html>\n";
	}
	
	/**
	* Prints the page body.
	* @param $bodyClass - name of body class
	*/
	function utl_printBody($bodyClass = '', $onload='', $onsubmit='') 
	{
		$bodyClass = htmlspecialchars($bodyClass);
		echo "<body ", ($bodyClass == '' ? ' ' : " class=\"{$bodyClass}\" "), 
		($onload == '' ? '' : " onload=\"{$onload}\" "),
		($onsubmit == '' ? '' : " onsubmit=\"{$onsubmit}\" "),
		 ">\n";
	}
	
	/**
	* Prints the HTML header (H1,.. Hn)
	* @param int    $size  header font size
	* @param string $title title to print
	*/
	function utl_printTitle($title, $size = 1, $class = '') {
		$class = ($class != '') ? " class=\"$class\"" : '';
		echo "<h$size".$class.">$title</h$size>\n";
	}
	
	/** Convierte la cadena aaaa-mm-dd a dd/mm/aaaa */
	function utl_Formatea_fecha( &$cadena )
	{
		if(strlen($cadena)>0)
		{
				$pattern = '/-/';
				$v_fecha= preg_split($pattern, trim($cadena), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
				$cadena = $v_fecha[2]. '/'. $v_fecha[1] . '/'. $v_fecha[0]; 
		}
	}
	
	/** Convierte la cadena dd/mm/aaaa a aaaa-mm-dd */
	function utl_Formatea_fecha_pg( &$cadena )
	{
		if(strlen($cadena)>0)
		{
			$pattern = '/\//';
			$v_fecha= preg_split($pattern, trim($cadena), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
			$cadena = $v_fecha[2]. '-'. $v_fecha[1] . '-'. $v_fecha[0]; 
			return $cadena;
		}
	}
	
	/** Calcula edad de una persona a partir de la fecha de nacimiento y una fecha actual
	* @param string $p_FecNac Fecha de nacimiento [AAAA-MM-DD]
	* @param string $p_FecAct Fecha actual [AAAA-MM-DD]
	* @return array Retorna una matriz de la forma matriz[item_registro][campo1][campo2]...[campon]
	*/
	function utl_Calcula_Edad($p_FecNac, $p_FecAct)
	{
		if(!$p_FecAct)
		{
			$p_FecAct=date("Y-m-d");
		}
		
		if( strlen($p_FecNac) < 0 )
		{
			echo "La fecha de nacimiento, para el calculo de la edad, no puede ser nula<br />";
			return 0;
		}
				
		if( strlen($p_FecAct) < 0 )
		{
			echo "La fecha actual, para el calculo de la edad, no puede ser nula<br />";
			return 0;
		}
				
		$v_pattern = '/-/';
		$v_FecNac= preg_split($v_pattern, trim($p_FecNac), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		$v_FecAct= preg_split($v_pattern, trim($p_FecAct), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
				
		if( (count($v_FecNac)!=3) )
		{
			echo "El formato de la fecha de nacimiento es INVALIDO [AAAA-MM-DD]<br />";
			return 0;
		}
				
		if( (count($v_FecAct)!=3) )
		{
			echo "El formato de la fecha actual es INVALIDO [AAAA-MM-DD]<br />";
			return 0;
		}
				
		$v_Edad = $v_FecAct[0]-$v_FecNac[0];
				
		if( ( $v_FecAct[1] < $v_FecNac[1] )
			|| ( $v_FecAct[1] == $v_FecNac[1] && $v_FecAct[2] < $v_FecNac[2]) )
			$v_Edad=$v_Edad-1;
		
		return $v_Edad;
	}
	
	/** Funcion que Agrega un mes a una fecha dada
	* @param $p_FecCar: Fecha de carga, en formato dd/mm/aaaa
	* @param $p_mes:    Meses a agregar
	* @return Cadena del tipo dd/mm/aaaa con el mes incrementado
	*/
	function utl_AgregaMes($p_FecCar, $p_mes)
	{
		$pattern = '/\//';
		$v_fecha= preg_split($pattern, trim($p_FecCar), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		$p_FecCar=$v_fecha[1]. "/" . $v_fecha[0] . "/" . $v_fecha[2];
		$my_time = strtotime($p_FecCar);
		$nextmonth  = mktime(0, 0, 0, date("m", $my_time)+$p_mes,  date("d", $my_time),  date("Y", $my_time));
		return date("d/m/Y", $nextmonth);
	}
	/** Funcion que cuenta los registros devueltos por un query, este revisa el primer campo
	*   que por definicion debe ser parte de la clave y no debe ser nulo */
	function utl_count(&$pDatos)
	{
		$longDatos = sizeof($pDatos);
		if($longDatos == 1 )
		{
			$campoId   = key($pDatos[0]);
			if($pDatos[0][$campoId] == '' )
			{
				return 0;
			}
			return 1;
		}
		return $longDatos;
	}

	/** Verifica que la primer fecha sea mayor que la segunda
	Retorna 0 si la primera es mayor que la segunda
			1 si la segunda es mayor que la primera
	*/
	function utl_FechaMayorIgual( $p_fechaA, $p_fechaB )
	{
		//Cargar los arrays desde y hasta, de esta forma
		// array[0] = dia,  array[1] = mes,  array[2] = anio
		
		$v_pattern = '/\//';
		$v_array_fecha_A = preg_split($v_pattern, trim($p_fechaA), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		$v_array_fecha_B = preg_split($v_pattern, trim($p_fechaB), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		
		$v_dia_A=$v_array_fecha_A[0];
		$v_mes_A=$v_array_fecha_A[1];
		$v_anio_A=$v_array_fecha_A[2];
		
		$v_dia_B=$v_array_fecha_B[0];
		$v_mes_B=$v_array_fecha_B[1];
		$v_anio_B=$v_array_fecha_B[2];
		
		if( $v_anio_B < $v_anio_A) //Anio
			return 0;
		else
		{
			if( $v_anio_B == $v_anio_A)
			{
				if ( $v_mes_A > $v_mes_B ) //Mes
					return 0;
				else
				{
					if( $v_mes_B == $v_mes_A)
					{
						if( $v_dia_A > $v_dia_B) //Dia
							return 0;
					}
				}
			}
		}
		
		return 1;
	}
	
	function utl_Mensaje($ptipo, $pcod, $pmensaje, $pquery)
	{
		$return = '';
		$v_tipo=strtoupper($ptipo);
		$return .= '<strong><em style="color:#9933CC;">' . $pcod. "</em></strong>  ";
		
		if(trim($v_tipo) == "OK")
		{
			$return .= '<strong><em style="color:green;">Ok</em></strong> ';
		}
		if(trim($v_tipo) == "ERROR")
		{
			$return .= '<strong><em style="color:red;">Error: </em></strong>';
		}
		if(trim($v_tipo) == "ADVERTENCIA")
		{
			$return .= '<strong><em style="color:#FF9900;">Advertencia: </em></strong>';
		}
		
		
		
		$return .= '<em style="color:blue;">' . $pmensaje . '</em> ';
		
		if($pquery!='')
			$return .= ' - Consulta: <em style="color:blue;">' . $pquery . '</em>';
		
		$return.='<br />';
		
		return $return;
	}
	
?>