<?php
/**
 * Sifency Metabox Framework - Template Helper Functions
 *
 * These functions provide an easy way to retrieve and display metabox values
 *
 * @package Sifency
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * The core "Getter" function. Retrieves a raw meta value for a specific field.
 *
 * All other helper functions use this as a base.
 *
 * @param string   $field_id  The ID of the meta field to retrieve.
 * @param int|null $post_id The ID of the post. Defaults to the current post in the loop.
 * @param mixed    $default    The default value to return if the field is empty.
 * @return mixed The raw value of the meta field.
 */
function sifency_get_field( $field_id, $post_id = null, $default = '' ) {
	if ( null === $post_id ) {
		$post_id = get_the_ID();
	}

	if ( ! $post_id && ( function_exists( 'is_singular' ) && is_singular() ) ) {
		$post_id = get_queried_object_id();
	}

	if ( ! $post_id ) {
		return $default;
	}

	$value = get_post_meta( $post_id, $field_id, true );

	if ( '' !== $value && ! empty( $value ) ) {
		return $value;
	}

	$all_meta = get_post_meta( $post_id );
	if ( ! empty( $all_meta ) && is_array( $all_meta ) ) {
		foreach ( $all_meta as $meta_key => $meta_values ) {
			$first = is_array( $meta_values ) ? ( $meta_values[0] ?? null ) : null;
			if ( is_array( $first ) && array_key_exists( $field_id, $first ) ) {
				$found = $first[ $field_id ];
				return '' !== $found ? $found : $default;
			}
		}
	}

	return $default;
}

/**
 * Checks if a field has a value.
 *
 * Useful for conditionals in templates. e.g., if ( sifency_has_field('my_field') ) { ... }
 *
 * @param string   $field_id  The ID of the meta field to check.
 * @param int|null $post_id The ID of the post. Defaults to the current post in the loop.
 * @return bool True if the field has a non-empty value, false otherwise.
 */
function sifency_has_field( $field_id, $post_id = null ) {
	$value = sifency_get_field( $field_id, $post_id );
	return ! empty( $value );
}

/**
 * Displays a simple text-based field with HTML escaping.
 *
 * Ideal for: text, select, button_set, email, url, number, date, time.
 *
 * @param string   $field_id The ID of the field.
 * @param int|null $post_id The ID of the post.
 * @param string   $default  Default text to display if empty.
 */
function sifency_the_field( $field_id, $post_id = null, $default = '' ) {
	echo esc_html( sifency_get_field( $field_id, $post_id, $default ) );
}

/**
 * Displays a field with potentially rich HTML content, applying content filters.
 *
 * Ideal for: wp_editor, textarea (that contains HTML).
 *
 * @param string   $field_id The ID of the field.
 * @param int|null $post_id The ID of the post.
 */
function sifency_the_content_field( $field_id, $post_id = null ) {
	$content = sifency_get_field( $field_id, $post_id );
	if ( $content ) {
		echo wp_kses_post( apply_filters( 'the_content', $content ) );
	}
}

/**
 * Retrieves the URL from a media or upload field.
 *
 * @param string   $field_id The ID of the media/upload field.
 * @param int|null $post_id The ID of the post.
 * @param string   $size      For 'media' fields, the desired image size (e.g., 'thumbnail', 'medium', 'large', 'full').
 * @return string The URL of the attachment, or an empty string if not found.
 */
function sifency_get_attachment_url( $field_id, $post_id = null, $size = 'full' ) {
	$attachment_id = sifency_get_field( $field_id, $post_id );
	if ( ! $attachment_id ) {
		return '';
	}

	$url = wp_get_attachment_image_url( $attachment_id, $size );
	if ( ! $url ) {
		$url = wp_get_attachment_url( $attachment_id );
	}
	return $url ? esc_url( $url ) : '';
}

/**
 * Displays a full <img> tag from a media field.
 *
 * @param string   $field_id The ID of the media field.
 * @param int|null $post_id The ID of the post.
 * @param string   $size      The image size to display.
 * @param array    $attr       Additional attributes for the <img> tag (e.g., ['class' => 'my-class']).
 */
function sifency_the_image_field( $field_id, $post_id = null, $size = 'full', $attr = array() ) {
	$attachment_id = sifency_get_field( $field_id, $post_id );
	if ( $attachment_id ) {
		echo wp_get_attachment_image( $attachment_id, $size, false, $attr );
	}
}

/**
 * Renders a link (<a> tag) from a URL field.
 *
 * @param string   $field_id    The ID of the URL field.
 * @param int|null $post_id   The ID of the post.
 * @param array    $args         {
 *        Optional. An array of arguments.
 *     @type string $text     The link text. Defaults to the URL itself.
 *     @type string $class    CSS class for the <a> tag.
 *     @type bool   $new_tab  Whether to open the link in a new tab. Defaults to true.
 * }
 */
function sifency_the_link_field( $field_id, $post_id = null, $args = array() ) {
	$url = sifency_get_field( $field_id, $post_id );
	if ( ! $url ) {
		return;
	}

	$defaults = array(
		'text'    => $url,
		'class'   => '',
		'new_tab' => true,
	);
	$args     = wp_parse_args( $args, $defaults );

	$target    = $args['new_tab'] ? ' target="_blank" rel="noopener noreferrer"' : '';
	$class     = $args['class'] ? ' class="' . esc_attr( $args['class'] ) . '"' : '';
	$link_text = esc_html( $args['text'] );

	echo '<a href="' . esc_url( $url ) . '"'
	. ( ! empty( $class ) ? ' class="' . esc_attr( $class ) . '"' : '' )
	. ( ! empty( $target ) ? ' target="' . esc_attr( $target ) . '"' : '' )
	. '>'
	. esc_html( $link_text )
	. '</a>';
}

/**
 * Gets formatted file size from an attachment ID.
 *
 * @param int $attachment_id The ID of the attachment.
 * @return string The formatted file size (e.g., "1.2 MB", "256 KB").
 */
if ( ! function_exists( 'sifency_get_formatted_attachment_size' ) ) {
	function sifency_get_formatted_attachment_size( $attachment_id ) {
		$filepath = get_attached_file( $attachment_id );
		if ( ! $filepath || ! file_exists( $filepath ) ) {
			return '';
		}
		return size_format( filesize( $filepath ) );
	}
}
