<?php
/**
 * Load the dynamic author archive template for Author Kit.
 *
 * This handles header/footer logic, retrieves necessary author data,
 * and includes the selected template from the plugin.
 *
 * @package AUhtor_kit
 */


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// Load template file name from options.
$template_path = plugin_dir_path( __FILE__ ) . 'archive-template-default.php';

// Detect classic theme support.
$supports_classic_theme = function_exists( 'get_header' ) && function_exists( 'get_footer' );

// Start output buffering.
ob_start();

// Theme compatibility handling.
if ( $supports_classic_theme ) {
	get_header(); // Classic theme header.
} elseif ( function_exists( 'wp_body_open' ) ) {
	wp_body_open(); // Fallback for block themes.
}

// Only include the template if it exists.
if ( file_exists( $template_path ) ) {

	// Prepare author data.
	$author_id         = get_queried_object_id();
	$nicename          = author_kit_display_name( $author_id );
	$avatar            = get_avatar_url( $author_id );
	$display_name      = get_the_author_meta( 'display_name', $author_id );
	$alt_text          = $display_name . ' Avatar';
	$description       = get_the_author_meta( 'description', $author_id );
	$designation       = get_the_author_meta( 'author_kit_author_job_title', $author_id );
	$date_joined_raw   = get_the_author_meta( 'user_registered', $author_id );
	$date_joined       = date_i18n( get_option( 'date_format' ), strtotime( $date_joined_raw ) );
	$total_posts       = count_user_posts( $author_id );
	$social_profiles   = author_kit_get_social_profiles( $author_id );
	$meta_display_type = get_theme_mod( 'author_kit_archive_scribe_meta_type', 'label-button-style' );
	$link_attributes   = author_kit_get_link_attributes();
	$contact_email     = get_the_author_meta( 'author_kit_user_contact_email', $author_id );
	$company           = get_the_author_meta( 'author_kit_user_company', $author_id );
	$job_title         = get_the_author_meta( 'author_kit_author_job_title', $author_id );

	// Pass variables into a limited scope using an anonymous function.
	( function () use (
		$template_path,
		$author_id,
		$nicename,
		$avatar,
		$display_name,
		$alt_text,
		$description,
		$designation,
		$date_joined,
		$total_posts,
		$social_profiles,
		$meta_display_type,
		$link_attributes,
		$contact_email,
		$company,
		$job_title
	) {
		include $template_path;
	} )();

} else {
	echo '<p>' . esc_html__( 'The specified archive template file could not be found.', 'author-kit' ) . '</p>';
}

// Capture and clean output buffer.
$template_content = ob_get_clean();
// Only outputing previously escaped and safe content.
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $template_content;

// Footer output for classic themes.
if ( $supports_classic_theme ) {
	get_footer();
}
