<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Typography;
use \Elementor\Repeater;
use \Elementor\Icons_Manager;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use \Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Author_Box_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Flex_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Widget_Authorbox extends Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Author_Box_Controls;
	use Sifency_Addons_Flex_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'          => 'author-box-sifency',
			'title'         => 'Sifency Author Box',
			'icon'          => 'eicon-user-circle-o',
			'category'      => 'sifency-post-components',
			'keywords'      => array( 'author', 'box', 'bio', 'profile' ),
			'style_depends' => array( 'sifency-typo-style', 'sifency-frontend-style', 'sifency-icon', 'sifency-post-single-style' ),
		);
	}

	// =========================================================================
	// CONTROLS
	// =========================================================================

	protected function register_controls() {
		$this->add_sifency_author_box_controls();

		$this->add_sifency_addons_help_controls();

		$this->add_sifency_addons_image_style_controls(
			array(
				'selector'  => '.sifency-author-box__avatar .sifency-image img',
				'selectors' => array(
					'image'      => '.sifency-author-box__avatar .sifency-image img',
					'container'  => '.sifency-author-box__avatar .sifency-image img',
					'dimensions' => '.sifency-author-box__avatar .sifency-image img',
				),
			)
		);

		$this->update_control(
			'image_style_section',
			array(
				'label' => __( 'Author Image', 'sifency-addons' ),
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'   => 'heading_style',
				'label'    => 'Author Name',
				'selector' => '.sifency-heading-style',
				'exclude'  => array( 'tabs', 'transition' ),
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'content_style',
				'label'      => 'Author Bio',
				'selector'   => '.sifency-content-style',
				'color_only' => true,
				'exclude'    => array( 'tabs', 'transition', 'bg', 'border', 'radius', 'stroke' ),
			)
		);

		$this->add_authorbox_icon_style_controls();

		$this->start_controls_section(
			'section_layout',
			array(
				'label' => 'Layout Settings',
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_sifency_addons_flex_alignment_controls(
			array(
				'prefix'   => 'content_box_',
				'label'    => 'Flexbox Configuration',
				'selector' => '.sifency-author-box',
			)
		);

		$this->add_responsive_control(
			'social_align',
			array(
				'label'     => esc_html__( 'Social Icon Align', 'sifency-addons' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'flex-start'    => array(
						'title' => 'Start',
						'icon'  => 'eicon-flex eicon-justify-start-h',
					),
					'center'        => array(
						'title' => 'Center',
						'icon'  => 'eicon-flex eicon-justify-center-h',
					),
					'flex-end'      => array(
						'title' => 'End',
						'icon'  => 'eicon-flex eicon-justify-end-h',
					),
					'space-between' => array(
						'title' => 'Space Between',
						'icon'  => 'eicon-flex eicon-justify-space-between-h',
					),
					'space-around'  => array(
						'title' => 'Space Around',
						'icon'  => 'eicon-flex eicon-justify-space-around-h',
					),
				),
				'selectors' => array(
					'.sifency-author-box__social' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();

		$this->add_Sifency_Addons_Animation_Controls();

		$this->update_control(
			'sifency_animation_target',
			array(
				'type'    => Controls_Manager::HIDDEN,
				'default' => 'wrapper',
			)
		);
	}

	// =========================================================================
	// PRIVATE HELPERS
	// =========================================================================

	/**
	 * Resolves an Elementor media-field array to a usable URL.
	 *
	 * Priority:
	 *   1. wp_get_attachment_url( $id ) — always current-site correct; survives XML / OCDI import.
	 *   2. Stored URL                   — last resort; may be stale after import.
	 *
	 * @param  array $media_field  e.g. $settings['custom_author_avatar'] = ['id' => 12, 'url' => '...']
	 * @return string               Resolved URL or empty string.
	 */
	private function resolve_media_url( array $media_field ): string {
		$id  = ! empty( $media_field['id'] ) ? (int) $media_field['id'] : 0;
		$url = ! empty( $media_field['url'] ) ? $media_field['url'] : '';

		if ( $id > 0 ) {
			$resolved = wp_get_attachment_url( $id );
			if ( ! empty( $resolved ) ) {
				return $resolved;
			}
		}

		return $url;
	}

	// =========================================================================
	// RENDER
	// =========================================================================

	protected function render(): void {
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );

		$author_name        = '';
		$author_bio         = '';
		$author_avatar_html = '';

		if ( 'current' === $settings['source'] ) {
			// ── Current post author ───────────────────────────────────────────
			if ( ! get_the_author_meta( 'ID' ) ) {
				if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
					echo '<div class="sifency-placeholder">'
						. esc_html__( 'Author Box is set to "Current Post Author" but no author was found. Make sure you are on a Single Post page or set the preview in Theme Builder.', 'sifency-addons' )
						. '</div>';
				}
				return;
			}

			$author_name = get_the_author();
			$author_bio  = get_the_author_meta( 'description' );
			// get_avatar() is always current-site-correct — no ID resolve needed.
			$author_avatar_html = get_avatar( get_the_author_meta( 'ID' ), 240 );

		} else {
			// ── Custom author ─────────────────────────────────────────────────
			$author_name = $settings['custom_author_name'] ?? '';
			$author_bio  = $settings['custom_author_bio'] ?? '';

			// Resolve avatar URL from attachment ID so it survives XML / OCDI import.
			$avatar_field = $settings['custom_author_avatar'] ?? array();
			$avatar_url   = $this->resolve_media_url( $avatar_field );

			if ( ! empty( $avatar_url ) ) {
				$author_avatar_html = '<img src="' . esc_url( $avatar_url ) . '" alt="' . esc_attr( $author_name ) . '" />';
			}
		}

		// ── Wrapper ───────────────────────────────────────────────────────────
		$wrapper_attrs   = $animation_manager->get_wrapper_attributes( array( 'sifency-author-box' ) );
		$author_name_tag = ! empty( $settings['link']['url'] ) ? 'a' : 'div';

		$this->add_render_attribute( 'author_name_tag', 'class', 'sifency-author-box__name sifency-heading-style' );
		if ( 'a' === $author_name_tag ) {
			$this->add_link_attributes( 'author_name_tag', $settings['link'] );
		}
		?>
		<div 
		<?php
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped by animation manager
			echo wp_kses_post( $wrapper_attrs );
		?>
		>

			<?php if ( $author_avatar_html ) : ?>
				<div class="sifency-author-box__avatar">
					<div class="sifency-image">
						<?php echo wp_kses_post( $author_avatar_html ); ?>
					</div>
					<div class="sifency-image-overlay"></div>
				</div>
			<?php endif; ?>

			<div class="sifency-author-box__text">

				<?php if ( $author_name ) : ?>
					<<?php echo tag_escape( $author_name_tag ); ?>
					<?php
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor render attributes
						echo wp_kses_post( $this->get_render_attribute_string( 'author_name_tag' ) );
					?>
					>
						<?php echo esc_html( $author_name ); ?>
					</<?php echo tag_escape( $author_name_tag ); ?>>
				<?php endif; ?>

				<?php if ( $author_bio ) : ?>
					<div class="sifency-author-box__bio sifency-content-style">
						<?php echo esc_html( $author_bio ); ?>
					</div>
				<?php endif; ?>

				<?php
				// ── Social icons ──────────────────────────────────────────────
				$has_valid_icon = false;
				if ( ! empty( $settings['social_icon_list'] ) ) {
					foreach ( $settings['social_icon_list'] as $item ) {
						if ( ! empty( $item['social_icon']['value'] ) ) {
							$has_valid_icon = true;
							break;
						}
					}
				}

				if ( $has_valid_icon ) :
					?>
					<div class="sifency-author-box__social">
						<?php
						foreach ( $settings['social_icon_list'] as $item ) :

							if ( empty( $item['social_icon']['value'] ) ) {
								continue;
							}

							$social_link_key = 'social-link-' . $item['_id'];

							if ( ! empty( $item['link']['url'] ) ) {
								$this->add_link_attributes( $social_link_key, $item['link'] );
							}

							$this->add_render_attribute( $social_link_key, 'class', 'sifency-icon-style' );
							?>
							<a 
							<?php
								// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor link attributes
								echo wp_kses_post( $this->get_render_attribute_string( $social_link_key ) );
							?>
							>
								<?php
								\Elementor\Icons_Manager::render_icon(
									$item['social_icon'],
									array( 'aria-hidden' => 'true' )
								);
								?>
							</a>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>

			</div><!-- /.sifency-author-box__text -->
		</div>
		<?php
	}
}
