<?php
/**
 * Template Tags
 *
 * Reusable template tags for theme templates.
 *
 * @package ROI_Theme
 * @since 1.0.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Display the site logo
 *
 * @since 1.0.0
 * @param array $args Logo arguments.
 */
function roi_site_logo( $args = array() ) {
	$defaults = array(
		'class' => 'site-logo',
		'width' => 200,
	);

	$args = wp_parse_args( $args, $defaults );

	if ( has_custom_logo() ) {
		$custom_logo_id = get_theme_mod( 'custom_logo' );
		$logo           = wp_get_attachment_image_src( $custom_logo_id, 'full' );

		if ( $logo ) {
			printf(
				'<a href="%1$s" class="%2$s" rel="home">
					<img src="%3$s" alt="%4$s" width="%5$d">
				</a>',
				esc_url( home_url( '/' ) ),
				esc_attr( $args['class'] ),
				esc_url( $logo[0] ),
				esc_attr( get_bloginfo( 'name' ) ),
				absint( $args['width'] )
			);
		}
	} else {
		printf(
			'<a href="%1$s" class="%2$s site-title" rel="home">%3$s</a>',
			esc_url( home_url( '/' ) ),
			esc_attr( $args['class'] ),
			esc_html( get_bloginfo( 'name' ) )
		);
	}
}

/**
 * Display the site description
 *
 * @since 1.0.0
 * @param array $args Description arguments.
 */
function roi_site_description( $args = array() ) {
	$description = get_bloginfo( 'description', 'display' );

	if ( ! $description ) {
		return;
	}

	$defaults = array(
		'class' => 'site-description',
		'tag'   => 'p',
	);

	$args = wp_parse_args( $args, $defaults );

	printf(
		'<%1$s class="%2$s">%3$s</%1$s>',
		esc_attr( $args['tag'] ),
		esc_attr( $args['class'] ),
		esc_html( $description )
	);
}

/**
 * Display post meta information
 *
 * @since 1.0.0
 * @param array $args Meta arguments.
 */
function roi_post_meta( $args = array() ) {
	$defaults = array(
		'show_date'     => true,
		'show_author'   => true,
		'show_comments' => true,
		'show_category' => true,
		'class'         => 'entry-meta',
	);

	$args = wp_parse_args( $args, $defaults );

	echo '<div class="' . esc_attr( $args['class'] ) . '">';

	if ( $args['show_date'] ) {
		roi_posted_on();
	}

	if ( $args['show_author'] ) {
		roi_posted_by();
	}

	if ( $args['show_category'] && 'post' === get_post_type() ) {
		$categories_list = get_the_category_list( esc_html__( ', ', 'roi' ) );
		if ( $categories_list ) {
			printf(
				'<span class="cat-links">%s</span>',
				$categories_list // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
	}

	if ( $args['show_comments'] && ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
		echo '<span class="comments-link">';
		comments_popup_link(
			sprintf(
				wp_kses(
					/* translators: %s: post title */
					__( '0 comentarios<span class="screen-reader-text"> en %s</span>', 'roi' ),
					array(
						'span' => array(
							'class' => array(),
						),
					)
				),
				wp_kses_post( get_the_title() )
			),
			sprintf(
				wp_kses(
					/* translators: %s: post title */
					__( '1 comentario<span class="screen-reader-text"> en %s</span>', 'roi' ),
					array(
						'span' => array(
							'class' => array(),
						),
					)
				),
				wp_kses_post( get_the_title() )
			),
			sprintf(
				wp_kses(
					/* translators: %s: post title */
					__( '% comentarios<span class="screen-reader-text"> en %s</span>', 'roi' ),
					array(
						'span' => array(
							'class' => array(),
						),
					)
				),
				wp_kses_post( get_the_title() )
			)
		);
		echo '</span>';
	}

	echo '</div>';
}

/**
 * Display post thumbnail
 *
 * @since 1.0.0
 * @param array $args Thumbnail arguments.
 */
function roi_post_thumbnail( $args = array() ) {
	if ( ! has_post_thumbnail() ) {
		return;
	}

	$defaults = array(
		'size'  => 'large',
		'class' => 'post-thumbnail',
		'link'  => true,
	);

	$args = wp_parse_args( $args, $defaults );

	if ( $args['link'] && ! is_single() ) {
		?>
		<a class="<?php echo esc_attr( $args['class'] ); ?>" href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
			<?php the_post_thumbnail( $args['size'] ); ?>
		</a>
		<?php
	} else {
		?>
		<div class="<?php echo esc_attr( $args['class'] ); ?>">
			<?php the_post_thumbnail( $args['size'] ); ?>
		</div>
		<?php
	}
}

/**
 * Display read more link
 *
 * @since 1.0.0
 * @param array $args Read more arguments.
 */
function roi_read_more( $args = array() ) {
	$defaults = array(
		'text'  => esc_html__( 'Leer más', 'roi' ),
		'class' => 'read-more',
	);

	$args = wp_parse_args( $args, $defaults );

	printf(
		'<a href="%1$s" class="%2$s">%3$s</a>',
		esc_url( get_permalink() ),
		esc_attr( $args['class'] ),
		esc_html( $args['text'] )
	);
}

/**
 * Display social sharing buttons
 *
 * @since 1.0.0
 * @param array $args Share arguments.
 */
function roi_social_share( $args = array() ) {
	$defaults = array(
		'title'    => esc_html__( 'Compartir:', 'roi' ),
		'networks' => array( 'facebook', 'twitter', 'linkedin', 'whatsapp' ),
		'class'    => 'social-share',
	);

	$args = wp_parse_args( $args, $defaults );

	$post_title = get_the_title();
	$post_url   = get_permalink();

	echo '<div class="' . esc_attr( $args['class'] ) . '">';

	if ( $args['title'] ) {
		echo '<span class="share-title">' . esc_html( $args['title'] ) . '</span>';
	}

	echo '<ul class="share-buttons">';

	foreach ( $args['networks'] as $network ) {
		$share_url  = '';
		$icon_class = 'share-' . $network;

		switch ( $network ) {
			case 'facebook':
				$share_url = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode( $post_url );
				break;

			case 'twitter':
				$share_url = 'https://twitter.com/intent/tweet?text=' . rawurlencode( $post_title ) . '&url=' . rawurlencode( $post_url );
				break;

			case 'linkedin':
				$share_url = 'https://www.linkedin.com/shareArticle?mini=true&url=' . rawurlencode( $post_url ) . '&title=' . rawurlencode( $post_title );
				break;

			case 'whatsapp':
				$share_url = 'https://api.whatsapp.com/send?text=' . rawurlencode( $post_title . ' ' . $post_url );
				break;
		}

		if ( $share_url ) {
			printf(
				'<li class="share-item">
					<a href="%1$s" class="%2$s" target="_blank" rel="noopener noreferrer" aria-label="%3$s">
						<span class="screen-reader-text">%4$s</span>
					</a>
				</li>',
				esc_url( $share_url ),
				esc_attr( $icon_class ),
				/* translators: %s: social network name */
				esc_attr( sprintf( __( 'Compartir en %s', 'roi' ), ucfirst( $network ) ) ),
				esc_html( ucfirst( $network ) )
			);
		}
	}

	echo '</ul>';
	echo '</div>';
}

/**
 * Display author bio box
 *
 * @since 1.0.0
 * @param array $args Author bio arguments.
 */
function roi_author_bio( $args = array() ) {
	// Only show on single posts.
	if ( ! is_single() ) {
		return;
	}

	$defaults = array(
		'class'        => 'author-bio',
		'show_avatar'  => true,
		'avatar_size'  => 80,
		'show_archive' => true,
	);

	$args = wp_parse_args( $args, $defaults );

	$author_id          = get_the_author_meta( 'ID' );
	$author_name        = get_the_author();
	$author_description = get_the_author_meta( 'description' );

	if ( empty( $author_description ) ) {
		return;
	}

	echo '<div class="' . esc_attr( $args['class'] ) . '">';

	if ( $args['show_avatar'] ) {
		echo '<div class="author-avatar">';
		echo get_avatar( $author_id, $args['avatar_size'] );
		echo '</div>';
	}

	echo '<div class="author-info">';
	echo '<h3 class="author-name">' . esc_html( $author_name ) . '</h3>';
	echo '<p class="author-description">' . wp_kses_post( $author_description ) . '</p>';

	if ( $args['show_archive'] ) {
		printf(
			'<a href="%1$s" class="author-link">%2$s</a>',
			esc_url( get_author_posts_url( $author_id ) ),
			/* translators: %s: author name */
			esc_html( sprintf( __( 'Ver todos los artículos de %s', 'roi' ), $author_name ) )
		);
	}

	echo '</div>';
	echo '</div>';
}

/**
 * Display related posts
 *
 * @since 1.0.0
 * @param array $args Related posts arguments.
 */
function roi_related_posts( $args = array() ) {
	// Only show on single posts.
	if ( ! is_single() || 'post' !== get_post_type() ) {
		return;
	}

	$defaults = array(
		'title'          => esc_html__( 'Artículos relacionados', 'roi' ),
		'posts_per_page' => 3,
		'order'          => 'DESC',
		'orderby'        => 'date',
		'class'          => 'related-posts',
	);

	$args = wp_parse_args( $args, $defaults );

	// Get current post categories.
	$categories = get_the_category();

	if ( empty( $categories ) ) {
		return;
	}

	$category_ids = array();
	foreach ( $categories as $category ) {
		$category_ids[] = $category->term_id;
	}

	// Query related posts.
	$related_query = new WP_Query(
		array(
			'category__in'        => $category_ids,
			'post__not_in'        => array( get_the_ID() ),
			'posts_per_page'      => $args['posts_per_page'],
			'order'               => $args['order'],
			'orderby'             => $args['orderby'],
			'ignore_sticky_posts' => 1,
		)
	);

	if ( ! $related_query->have_posts() ) {
		return;
	}

	echo '<aside class="' . esc_attr( $args['class'] ) . '">';

	if ( $args['title'] ) {
		echo '<h3 class="related-posts-title">' . esc_html( $args['title'] ) . '</h3>';
	}

	echo '<div class="related-posts-grid">';

	while ( $related_query->have_posts() ) {
		$related_query->the_post();
		?>
		<article class="related-post">
			<?php if ( has_post_thumbnail() ) : ?>
				<a href="<?php the_permalink(); ?>" class="related-post-thumbnail">
					<?php the_post_thumbnail( 'medium' ); ?>
				</a>
			<?php endif; ?>

			<h4 class="related-post-title">
				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
			</h4>

			<div class="related-post-meta">
				<time datetime="<?php echo esc_attr( get_the_date( DATE_W3C ) ); ?>">
					<?php echo esc_html( get_the_date() ); ?>
				</time>
			</div>
		</article>
		<?php
	}

	echo '</div>';
	echo '</aside>';

	wp_reset_postdata();
}

/**
 * Display table of contents for long posts
 *
 * @since 1.0.0
 * @param array $args TOC arguments.
 */
function roi_table_of_contents( $args = array() ) {
	global $post;

	if ( ! is_single() || ! isset( $post->post_content ) ) {
		return;
	}

	$defaults = array(
		'title'          => esc_html__( 'Tabla de contenidos', 'roi' ),
		'class'          => 'table-of-contents',
		'min_headings'   => 3,
		'heading_levels' => array( 'h2', 'h3' ),
	);

	$args = wp_parse_args( $args, $defaults );

	// Extract headings from content.
	$content = $post->post_content;
	preg_match_all( '/<(' . implode( '|', $args['heading_levels'] ) . ')[^>]*>(.*?)<\/\1>/i', $content, $matches, PREG_SET_ORDER );

	if ( count( $matches ) < $args['min_headings'] ) {
		return;
	}

	echo '<nav class="' . esc_attr( $args['class'] ) . '">';

	if ( $args['title'] ) {
		echo '<h2 class="toc-title">' . esc_html( $args['title'] ) . '</h2>';
	}

	echo '<ol class="toc-list">';

	foreach ( $matches as $index => $heading ) {
		$heading_text = wp_strip_all_tags( $heading[2] );
		$heading_id   = sanitize_title( $heading_text ) . '-' . $index;

		printf(
			'<li class="toc-item toc-%1$s"><a href="#%2$s">%3$s</a></li>',
			esc_attr( $heading[1] ),
			esc_attr( $heading_id ),
			esc_html( $heading_text )
		);
	}

	echo '</ol>';
	echo '</nav>';
}

/**
 * Display cookie consent notice
 *
 * @since 1.0.0
 * @param array $args Cookie notice arguments.
 */
function roi_cookie_notice( $args = array() ) {
	// Check if cookie consent has been given.
	if ( isset( $_COOKIE['roi_cookie_consent'] ) ) {
		return;
	}

	$defaults = array(
		'message'     => esc_html__( 'Este sitio utiliza cookies para mejorar su experiencia. Al continuar navegando, acepta nuestro uso de cookies.', 'roi' ),
		'accept_text' => esc_html__( 'Aceptar', 'roi' ),
		'learn_more'  => esc_html__( 'Más información', 'roi' ),
		'policy_url'  => get_privacy_policy_url(),
		'class'       => 'cookie-notice',
	);

	$args = wp_parse_args( $args, $defaults );

	?>
	<div class="<?php echo esc_attr( $args['class'] ); ?>" role="alert" aria-live="polite">
		<div class="cookie-notice-content">
			<p><?php echo esc_html( $args['message'] ); ?></p>
			<div class="cookie-notice-actions">
				<button type="button" class="cookie-notice-accept" id="cookie-notice-accept">
					<?php echo esc_html( $args['accept_text'] ); ?>
				</button>
				<?php if ( $args['policy_url'] ) : ?>
					<a href="<?php echo esc_url( $args['policy_url'] ); ?>" class="cookie-notice-learn-more">
						<?php echo esc_html( $args['learn_more'] ); ?>
					</a>
				<?php endif; ?>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Calcula tiempo de lectura estimado
 *
 * @since 1.0.0
 * @return string Tiempo de lectura (ej: "5 min de lectura")
 */
function roi_get_reading_time() {
    $content = get_post_field('post_content', get_the_ID());
    $word_count = str_word_count(strip_tags($content));
    $reading_time = ceil($word_count / 200); // 200 palabras por minuto

    if ($reading_time < 1) {
        $reading_time = 1;
    }

    return sprintf(_n('%s min de lectura', '%s min de lectura', $reading_time, 'roi-theme'), $reading_time);
}

