<?php

/**
* Funções utilitárias para o painel SGCWS da Code Tecnologia
*/

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

if (!function_exists('password_verify')) {
  // Verifica a existência de funções de password do PHP >= 5.5 , caso não exista inclui pela biblioteca
  // externa compatível, baixada de https://github.com/ircmaxell/password_compat
  // Necessita de PHP >= 5.3.7, i.e., nosso servidor 200 :-/
  require_once 'lib/password.php';
}

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, exceto quando tem o 'admin'
  if (!in_array('admin', $pages)) {
    $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_key'];
		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_url($str) {
  $split = explode('/', $str);
  for($i = 0; $i < count($split); $i++) {
    $split[$i] = urlencode($split[$i]);
  }
  $str = implode('/', $split);
  return sgcws_attr($str);
}

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

function sgcws_combo_key2multiplevalue($combo, $keys, $glue=', ') {
  $values = array();
  foreach($keys as $key) {
    if (array_key_exists($key, $combo)) {
      $values[] = $combo[$key];
    }
  }
  return implode($glue, $values);
}

// http://www.maurits.vdschee.nl/php_hide_email/
function sgcws_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 sgcws_combo_table($name, $id, $valorAtual, $table, $keyField, $valueField, $where='st_ativo=1', $canBeEmpty=true) {
  global $conexao;
  $sql = "select $keyField, $valueField from $table ";
  if (!empty($where)) {
    $sql .= 'where ' . $where;
  }
  $resultado = mysqli_query($conexao, $sql);
  if ($resultado) {
    $combo = array();
    if ($canBeEmpty) {
      $combo[''] = '';
    }
    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 . ' -->';
  }
}

function sgcws_excerpt($str, $size=150) {
  $str = strip_tags($str);
  $str = trim(html_entity_decode($str, ENT_NOQUOTES, 'utf-8'));
  if (strlen($str) > $size) {
    // 
    $str = preg_replace("/^(.{1,$size})(\s.*|$)/s", '\\1', $str);
    $str = htmlentities($str, ENT_NOQUOTES, 'utf-8');
    $str .= '&hellip;';
  } else {
    $str = $str;
    $str = htmlentities($str, ENT_NOQUOTES, 'utf-8');
  }
  return $str;
}

// prepara e executa uma query insert/update/delete, retornando false se der erro ou o número de linhas afetadas pela query se for sucesso
function _prepareAndExecute($sql, $values, &$errorMsg=null, $controlaTransacao=false) {
  global $conexao;
  $ok = false;
  $stmt = mysqli_prepare($conexao, $sql);
  $nCampos = substr_count($sql, '?');
  if ($controlaTransacao) {
    $conexao->query("START TRANSACTION");
  }
  if($stmt) {
    $types = str_repeat('s', $nCampos);
    for ($base = 0; $base < count($values); $base += $nCampos) {
      $params = array($stmt, $types);
      for ($i = 0; $i < $nCampos; $i++) {
        //$value = $values[$base + $i];
        $params[] = &$values[$base + $i];
      }
      // chama a função que vai 'bindar' os parâmetros na query
      call_user_func_array('mysqli_stmt_bind_param', $params);
      $ok = mysqli_stmt_execute($stmt);
      if ($ok === false) {
        if ($error) {
          $error = mysqli_error($conexao);
        } else {
          addError(mysqli_error($conexao));
        }
        break; // sai do for
      } else {
        $ok = mysqli_stmt_affected_rows($stmt);
      }
    }
    mysqli_stmt_close($stmt);
  } else {
    $ok = false;
    if ($error) {
      $error = mysqli_error($conexao) . ' - ' . $sql;
    } else {
      addError(mysqli_error($conexao) . ' - ' . $sql);
    }
  }
  if ($controlaTransacao) {
    if ($ok === false) {
      $conexao->query("ROLLBACK");
    } else {
      $conexao->query("COMMIT");
    }
  }
  return $ok;
}

// prepara e executa uma query select, retorna false se der erro, ou um array com os resultados da query
function _prepareAndQuery($sql, $values, &$errorMsg=null) {
  global $conexao;
  $result = false;
  $stmt = mysqli_prepare($conexao, $sql);
  if ($stmt) {
    $types = str_repeat('s', count($values));
    $params = array($stmt, $types);
    foreach($values as &$value) {
      $params[] = &$value;
    }
    // chama a função que vai 'bindar' os parâmetros na query
    call_user_func_array('mysqli_stmt_bind_param', $params);
    mysqli_stmt_execute($stmt);
    $result = my_fetch_assoc_stmt($stmt);
    mysqli_stmt_close($stmt);
  } else {
    $result = false;
    if ($errorMsg) {
      $errorMsg = mysqli_error($conexao) . ' - ' . $sql;
    } else {
      addError(mysqli_error($conexao) . ' - ' . $sql);
    }
  }

  return $result;
}

function sgcws_sanitize_field($name, $value) {
  if (sgcws_startsWith($name, 'dh_')) {
    if (empty($value)) {
      $value = null;
    } else {
      $value = date('Y-m-d H:i', date_timestamp_get(date_create_from_format('d/m/Y H:i', $value)));
    }
  } else if (sgcws_startsWith($name, 'vl_') or sgcws_startsWith($name, 'nr_')) {
    if (empty($value)) {
      $value = null;
    } else {
      $value = preg_replace('/,/i', '.', preg_replace('/[^0-9,]+/i', '', $value));
    }
  } else if (sgcws_startsWith($name, 'st_') or sgcws_startsWith($name, 'fl_')) {
    if ($value === 'on') {
      $value = '1';
    }
  } else if (sgcws_startsWith($name, 'id_')) {
    if (empty($value)) {
      $value = null;
    }
  }
  return $value;
}

function sgcws_format_field($name, $value) {
  if (sgcws_startsWith($name, 'dh_')) {
    if (!empty($value)) {
      //addMessage('<pre>' . var_export($value) . '</pre>');
      $value = date('d/m/Y H:i', date_timestamp_get(date_create_from_format('Y-m-d H:i:s', $value)));
    }
  }
  return $value;
}

function sgcws_startsWith($haystack, $needle) {
  $length = strlen($needle);
  return (substr($haystack, 0, $length) === $needle);
}

function sgcws_endsWith($haystack, $needle)
{
  $length = strlen($needle);
  if ($length == 0) {
    return true;
  }
  return (substr($haystack, -$length) === $needle);
}