<?php
//require_once 'connect.php';
global $conexao;

function sql_error($c) {
	return (AMBIENTE != 'prd' ? mysqli_error($c) : '');
}

// http://php.net/manual/pt_BR/mysqli-stmt.fetch.php#117275
/**
* Fetches the results of a prepared statement as an array of associative
* arrays such that each stored array is keyed by the result's column names.
* @param stmt   Must have been successfully prepared and executed prior to calling this function
* @param buffer Whether to buffer the result set; if true, results are freed at end of function
* @return An array, possibly empty, containing one associative array per result row
*/
function fetch_assoc_stmt(\mysqli_stmt $stmt, $buffer = true) {
    if ($buffer) {
        $stmt->store_result();
    }
    $fields = $stmt->result_metadata()->fetch_fields();
    $args = array();
    foreach($fields AS $field) {
        $key = str_replace(' ', '_', $field->name); // space may be valid SQL, but not PHP
        $args[$key] = &$field->name; // this way the array key is also preserved
    }
    call_user_func_array(array($stmt, "bind_result"), $args);
    $results = array();
    while($stmt->fetch()) {
        $results[] = array_map("sgcws_copy_value", $args);
    }
    if ($buffer) {
        $stmt->free_result();
    }
    return $results;
}

/**
 * Substitui o mysqli_fetch_assoc, que sempre da problema na nossa hospedagem
 * http://php.net/manual/pt_BR/mysqli-stmt.fetch.php#117275
 */
function my_fetch_assoc_stmt(\mysqli_stmt $stmt, $buffer = true) {
    if ($buffer) {
        $stmt->store_result();
    }
    $fields = $stmt->result_metadata()->fetch_fields();
    $args = array();
    foreach($fields AS $field) {
        $key = str_replace(' ', '_', $field->name); // space may be valid SQL, but not PHP
        $args[$key] = &$field->name; // this way the array key is also preserved
    }
    call_user_func_array(array($stmt, "bind_result"), $args);
    $results = array();
    while($stmt->fetch()) {
        $results[] = array_map("sgcws_copy_value", $args);
    }
    if ($buffer) {
        $stmt->free_result();
    }
    return $results;
}

/**
* Copy value as value
*/
function sgcws_copy_value($v) {
    return $v;
}

function sgcws_get_page_data($pages) {
	global $conexao;
	if (!$pages || empty($pages)) {
		$pages = array();
	} else if (!is_array($pages)) {
		$pages = array($pages);
	}
	// sempre adiciona o 'comum' para todos os carregamentos
	$pages[] = 'comum';
	// prepara a query
	$sql = 'select * from sgcws_conteudo where st_ativo = 1 and ds_pagina in (' . trim(str_repeat('?,', count($pages)), ',') . ')';
	$stmt = mysqli_prepare($conexao, $sql);
	// monta os parâmetros para bind
	$types = str_repeat('s', count($pages));
	$params = array($stmt, $types);
	foreach($pages as &$page) {
		$params[] = &$page;
	}
	// chama a função que vai 'bindar' os parâmetros na query
	call_user_func_array('mysqli_stmt_bind_param', $params);
	// executa a query e monta array com resultados, onde a chave será página:seção e no valor um array contendo os valores encontrados para aquela chave, assim
	// quando houver listas não terá problema
	mysqli_stmt_execute($stmt);
	/* Fetch result to array */
	/*
	$res = mysqli_stmt_get_result($stmt);
	$ret = array();
	while($row = mysqli_fetch_assoc($res)) {
		//var_dump($row);
		$key = $row['ds_pagina'] . ':' . $row['ds_secao'];
		if (!array_key_exists($key, $ret)) {
			$ret[$key] = array();
		}
		$ret[$key][] = $row;
	}
	mysqli_stmt_close($stmt);
	*/
	$result = my_fetch_assoc_stmt($stmt);
	$ret = array();
	foreach($result as $row) {
		$key = $row['ds_pagina'] . ':' . $row['ds_secao'];
		if (!array_key_exists($key, $ret)) {
			$ret[$key] = array();
		}
		$ret[$key][] = $row;
	}
	return $ret;
}

function sgcws_attr($str) {
	return htmlentities($str, ENT_QUOTES, 'utf-8');
}
function sgcws_html($str) {
	return htmlentities($str, ENT_NOQUOTES, 'utf-8');
}

function sgcws_combo_array($combo, $nomeCampo, $id="", $valorAtual="", $hideKeys=array()) {
  echo '<select name="' . $nomeCampo . '" class="form-control"' . (empty($id) ? '' : ' id="' . sgcws_attr($id) . '"') . '>';
  foreach($combo as $key => $value) {
    if (in_array($key, $hideKeys)) {
      // pula esta chave que é para esconder
      continue;
    }
    $selected = ($key === $valorAtual ? ' selected="selected" ' : '');
    echo "<option value='$key' $selected>$value</option>";
  }
  echo '</select>';
}

function sgcws_combo_key2value($combo, $key, $default="") {
  return array_key_exists($key, $combo) ? $combo[$key] : $default;
}

// http://www.maurits.vdschee.nl/php_hide_email/
function hide_email($email) {
  $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  $key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999);
  for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])];
  $script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
  $script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
  $script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\\"mailto:"+d+"\\">"+d+"</a>"';
  $script = "eval(\"".str_replace(array("\\",'"'),array("\\\\",'\"'), $script)."\")"; 
  $script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>';
  return '<span id="'.$id.'">[javascript protected email address]</span>'.$script;
}

function links_doador() {
  if (isset($_SESSION['doador'])) {
    $doador = $_SESSION['doador'];
    echo '<p class="pull-right">Olá ' . $doador['nome'] . '. <a href="doador_painel.php">Painel</a> | <a href="doador_cadastro.php">Perfil</a> | <a href="doador_logout.php">Sair</a></p>';
  }
}

function sgcws_combo_table($name, $id, $valorAtual, $table, $keyField, $valueField, $where = 'st_ativo = 1') {
  global $conexao;
  $sql = "select $keyField, $valueField from $table ";
  if (!empty($where)) {
    $sql .= 'where ' . $where;
  }
  $resultado = mysqli_query($conexao, $sql);
  if ($resultado) {
    $combo = array();
    while($registro = mysqli_fetch_assoc ($resultado)) {
      $keys = array_keys($registro);
      $combo[$registro[$keys[0]]] = $registro[$keys[1]];
    };
    sgcws_combo_array($combo, $name, $id, $valorAtual);
  } else {
    $erro = mysqli_error($conexao);
    echo '<div class="alert alert-danger">OPS! Problemas aqui, contate o administrador</div><!-- ' . PHP_EOL . sgcws_html($erro) . PHP_EOL . $sql . PHP_EOL . ' -->';
  }
}
