/**
* Funciones auxiliares y utilidades
* Preserva todas las funciones helper del código original
*/
if (!defined('ABSPATH')) {
exit;
}
class Psicolat_Helpers {
/**
* Instancia única
*/
private static $instance = null;
/**
* Obtener instancia única
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor privado
*/
private function __construct() {}
/**
* Obtener etiquetas de glosario JetEngine
*/
public function get_jetengine_glossary_labels($glossary_id) {
if (!function_exists('jet_engine') || !method_exists(jet_engine()->glossaries->data, 'get_glossary_for_field')) {
return [];
}
$glossary = jet_engine()->glossaries->data->get_glossary_for_field($glossary_id);
if (empty($glossary)) {
return [];
}
$labels = [];
foreach ($glossary as $item) {
if (isset($item['value']) && isset($item['label'])) {
$labels[$item['value']] = $item['label'];
}
}
return $labels;
}
/**
* Obtener opciones de modalidad de atención
*/
public function get_modalidad_atencion_options() {
return [
'adultos' => 'Adultos',
'ninezyadolescencia' => 'Niñez y Adolescencia',
'grupal' => 'Grupal',
'parejas' => 'Parejas',
'amigosyfamilia' => 'Amigos y Familia'
];
}
/**
* Obtener label de modalidad de atención
*/
public function get_modalidad_atencion_label($value) {
if (empty($value)) return '';
$opciones = $this->get_modalidad_atencion_options();
return $opciones[$value] ?? 'Desconocido';
}
/**
* Obtener opciones de medios de pago
*/
public function get_medios_de_pago_options() {
return $this->get_jetengine_glossary_labels(18);
}
/**
* Obtener slugs de taxonomías de especialización
*/
public function get_specialization_taxonomy_slugs() {
return [
'traumas', 'problemas-legales', 'problemas-de-salud-mental',
'problemas-de-salud-en-general', 'problemas-laborales', 'evaluaciones-y-tests',
'dificultades-personales', 'dificultades_en_el_aprendizaje', 'adicciones',
'orientaciones-teoricas'
];
}
/**
* Obtener miniatura apropiada para un attachment
*/
public function get_attachment_thumbnail($attachment_id, $mime_type = null) {
if (!$mime_type) $mime_type = get_post_mime_type($attachment_id);
if ($mime_type === 'application/pdf') {
$thumbnail = wp_get_attachment_image_src($attachment_id, 'thumbnail');
return $thumbnail ? $thumbnail[0] : wp_mime_type_icon('application/pdf');
} elseif (strpos($mime_type, 'image/') === 0) {
$thumbnail = wp_get_attachment_image_src($attachment_id, 'thumbnail');
return $thumbnail ? $thumbnail[0] : wp_get_attachment_url($attachment_id);
}
return wp_mime_type_icon($attachment_id);
}
/**
* Calcular edad a partir de fecha de nacimiento
*/
public function calculate_age($birth_date) {
if (empty($birth_date)) return 'No especificada';
$birth = new DateTime($birth_date);
$today = new DateTime();
$age = $today->diff($birth);
return $age->y;
}
/**
* Formatear fecha
*/
public function format_date($date, $format = 'd/m/Y') {
if (empty($date)) return '';
try {
$datetime = new DateTime($date);
return $datetime->format($format);
} catch (Exception $e) {
return $date;
}
}
/**
* Renderizar lista de títulos
*/
public function render_titulos_list($titulos) {
if (empty($titulos)) return '
No hay títulos registrados.
';
$html = '';
foreach ($titulos as $titulo) {
$html .= '- ';
$html .= '';
$html .= '
';
$html .= '
' . esc_html($titulo['nombre']) . '
';
if (!empty($titulo['institucion'])) {
$html .= '
' . esc_html($titulo['institucion']) . '
';
}
if (!empty($titulo['ano'])) {
$html .= '
Año: ' . esc_html($titulo['ano']) . '
';
}
if (!empty($titulo['certificados'])) {
$html .= '
';
$html .= $this->render_certificate_gallery($titulo['certificados']);
$html .= '
';
}
$html .= '
';
$html .= ' ';
}
$html .= '
';
return $html;
}
/**
* Renderizar lista de postgrados
*/
public function render_postgrados_list($postgrados) {
if (empty($postgrados)) return 'No hay postgrados registrados.
';
$html = '';
foreach ($postgrados as $postgrado) {
$html .= '- ';
$html .= '';
$html .= '
';
$tipo_label = $this->get_postgrado_type_label($postgrado['tipo']);
$html .= '
';
$html .= '' . esc_html($tipo_label) . ': ';
$html .= esc_html($postgrado['nombre']);
$html .= '
';
if (!empty($postgrado['institucion'])) {
$html .= '
' . esc_html($postgrado['institucion']) . '
';
}
if (!empty($postgrado['ano'])) {
$html .= '
Año: ' . esc_html($postgrado['ano']) . '
';
}
if (!empty($postgrado['certificados'])) {
$html .= '
';
$html .= $this->render_certificate_gallery($postgrado['certificados']);
$html .= '
';
}
$html .= '
';
$html .= ' ';
}
$html .= '
';
return $html;
}
/**
* Obtener label de tipo de postgrado
*/
private function get_postgrado_type_label($tipo) {
$tipos = [
'_curso' => 'Curso',
'_postitulo' => 'Postítulo',
'_pasantia' => 'Pasantía',
'_taller' => 'Taller',
'supervision' => 'Supervisión'
];
return $tipos[$tipo] ?? 'Formación';
}
/**
* Renderizar galería de certificados
*/
private function render_certificate_gallery($certificados) {
if (empty($certificados)) return '';
$html = '';
foreach ($certificados as $cert_id) {
if (!$cert_id) continue;
$attachment_url = wp_get_attachment_url($cert_id);
$attachment_title = get_the_title($cert_id);
$mime_type = get_post_mime_type($cert_id);
$thumbnail_url = $this->get_attachment_thumbnail($cert_id, $mime_type);
if ($mime_type === 'application/pdf') {
$html .= '
';
$html .= '
';
$html .= '';
$html .= '';
} else {
$html .= '
';
$html .= '
';
$html .= '';
}
}
$html .= '
';
return $html;
}
/**
* Sanitizar array recursivamente
*/
public function sanitize_array_recursive($array) {
if (!is_array($array)) {
return sanitize_text_field($array);
}
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = $this->sanitize_array_recursive($value);
} else {
$array[$key] = sanitize_text_field($value);
}
}
return $array;
}
/**
* Verificar si un valor está en un array (helper para checkboxes)
*/
public function is_checked($value, $array) {
return is_array($array) && in_array($value, $array);
}
/**
* Generar ID único para elementos del DOM
*/
public function generate_unique_id($prefix = 'psicolat') {
return $prefix . '_' . wp_generate_password(8, false);
}
/**
* Obtener URL de imagen por defecto
*/
public function get_default_image_url() {
return 'https://via.placeholder.com/150x150/e5e7eb/9ca3af?text=Sin+Foto';
}
/**
* Formatear número de teléfono
*/
public function format_phone_number($phone) {
// Remover caracteres no numéricos
$phone = preg_replace('/[^0-9]/', '', $phone);
// Si el número tiene formato chileno (9 dígitos)
if (strlen($phone) === 9) {
return '+56 ' . substr($phone, 0, 1) . ' ' .
substr($phone, 1, 4) . ' ' . substr($phone, 5, 4);
}
return $phone;
}
/**
* Obtener términos de una taxonomía formateados para select
*/
public function get_taxonomy_terms_for_select($taxonomy) {
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
]);
if (is_wp_error($terms)) {
return [];
}
$options = [];
foreach ($terms as $term) {
$options[$term->term_id] = $term->name;
}
return $options;
}
/**
* Verificar si una URL es válida
*/
public function is_valid_url($url) {
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
/**
* Obtener el tipo de red social desde una URL
*/
public function get_social_network_type($url) {
$patterns = [
'facebook.com' => 'facebook',
'instagram.com' => 'instagram',
'twitter.com' => 'twitter',
'x.com' => 'twitter',
'linkedin.com' => 'linkedin',
'youtube.com' => 'youtube',
'tiktok.com' => 'tiktok',
];
foreach ($patterns as $domain => $type) {
if (strpos($url, $domain) !== false) {
return $type;
}
}
return 'website';
}
/**
* Generar mensaje de error amigable
*/
public function get_friendly_error_message($error_code) {
$messages = [
'invalid_file_type' => 'El tipo de archivo no es válido. Solo se permiten imágenes y PDFs.',
'file_too_large' => 'El archivo es demasiado grande. El tamaño máximo es 5MB.',
'upload_failed' => 'Error al subir el archivo. Por favor, intenta nuevamente.',
'invalid_data' => 'Los datos proporcionados no son válidos.',
'permission_denied' => 'No tienes permisos para realizar esta acción.',
];
return $messages[$error_code] ?? 'Ha ocurrido un error. Por favor, intenta nuevamente.';
}
}
?>