<?php
/**
 * Chronicle Journal Theme Functions
 *
 * This file contains all the core functionality for the Chronicle Journal WordPress theme.
 * It includes theme setup, asset enqueuing, custom functions, and WordPress integrations.
 *
 * @package Chronicle_Journal
 * @since 1.0.0
 * @version 1.0.0
 * @author Rolly Bueno
 * @license GPL-2.0-or-later
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 * @link https://developer.wordpress.org/themes/block-themes/
 */
// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Enqueue theme styles and scripts
 *
 * This function handles the enqueuing of all theme assets including CSS and JavaScript files.
 * It uses file modification time for cache busting to ensure users get the latest version
 * of assets when they're updated.
 *
 * @since 1.0.0
 * @return void
 *
 * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
 * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
 */
function chronicle_journal_enqueue_assets() {
	// Define asset paths
	$css_file = get_template_directory() . '/assets/css/main.css';
	$css_url  = get_template_directory_uri() . '/assets/css/main.css';

	// Enqueue main CSS file with cache busting
	wp_enqueue_style(
		'chronicle-journal-main',           // Handle
		$css_url,                          // URL
		array(),                           // Dependencies
		filemtime( $css_file ),            // Version (cache busting)
		'all'                              // Media
	);
}
add_action( 'wp_enqueue_scripts', 'chronicle_journal_enqueue_assets' );

/**
 * Add theme support for various features
 *
 * This function sets up theme support for various WordPress features and block editor
 * capabilities. It's called during the 'after_setup_theme' hook to ensure all
 * theme features are properly registered.
 *
 * @since 1.0.0
 * @return void
 *
 * @link https://developer.wordpress.org/reference/functions/add_theme_support/
 * @link https://developer.wordpress.org/block-editor/reference-guides/theme-support/
 */
function chronicle_journal_theme_setup() {
	/**
	 * RSS Feed Links
	 * Adds default posts and comments RSS feed links to head
	 */
	add_theme_support( 'automatic-feed-links' );

	/**
	 * Document Title
	 * Let WordPress manage the document title for better SEO
	 */
	add_theme_support( 'title-tag' );

	/**
	 * Post Thumbnails
	 * Enable support for featured images on posts and pages
	 */
	add_theme_support( 'post-thumbnails' );

	/**
	 * Responsive Embeds
	 * Makes embeds responsive by default
	 */
	add_theme_support( 'responsive-embeds' );

	/**
	 * Custom Line Height
	 * Enables custom line height controls in the block editor
	 */
	add_theme_support( 'custom-line-height' );

	/**
	 * Experimental Link Color
	 * Enables experimental link color control in the block editor
	 */
	add_theme_support( 'experimental-link-color' );

	/**
	 * Custom Units
	 * Enables custom CSS units in the block editor
	 */
	add_theme_support( 'custom-units' );

	/**
	 * Custom Spacing Scale
	 * Enables custom spacing scale controls in the block editor
	 */
	add_theme_support( 'custom-spacing' );

	/**
	 * Editor Styles
	 * Enables custom styles in the block editor
	 */
	add_theme_support( 'editor-styles' );

	/**
	 * Wide Alignment
	 * Enables wide and full-width alignment options
	 */
	add_theme_support( 'align-wide' );

	/**
	 * HTML5 Markup
	 * Enables HTML5 markup for various elements
	 */
	add_theme_support(
		'html5',
		array(
			'search-form',    // Search form
			'comment-form',   // Comment form
			'comment-list',   // Comment list
			'gallery',        // Gallery
			'caption',        // Caption
			'style',          // Style
			'script',         // Script
		)
	);
}
add_action( 'after_setup_theme', 'chronicle_journal_theme_setup' );

/**
 * Add custom image sizes
 *
 * This function registers custom image sizes for the theme. These sizes are used
 * throughout the theme for different display contexts and help optimize image loading.
 *
 * @since 1.0.0
 * @return void
 *
 * @link https://developer.wordpress.org/reference/functions/add_image_size/
 */
function chronicle_journal_image_sizes() {
	/**
	 * Featured Image Size
	 * Used for hero sections and featured posts
	 * Dimensions: 1200x600px (2:1 aspect ratio)
	 */
	add_image_size( 'chronicle-featured', 1200, 600, true );

	/**
	 * Thumbnail Size
	 * Used for post thumbnails and grid layouts
	 * Dimensions: 400x300px (4:3 aspect ratio)
	 */
	add_image_size( 'chronicle-thumbnail', 400, 300, true );
}
add_action( 'after_setup_theme', 'chronicle_journal_image_sizes' );

/**
 * Add editor styles support
 *
 * This function adds custom styles to the block editor to ensure the editing
 * experience matches the front-end appearance as closely as possible.
 *
 * @since 1.0.0
 * @return void
 *
 * @link https://developer.wordpress.org/reference/functions/add_editor_style/
 */
function chronicle_journal_add_editor_styles() {
	/**
	 * Main Editor Styles
	 * Applies the main theme CSS to the block editor
	 */
	add_editor_style( 'assets/css/main.css' );
}
add_action( 'after_setup_theme', 'chronicle_journal_add_editor_styles' );

/**
 * Customize the excerpt length
 *
 * This function modifies the default excerpt length for posts. It's used
 * to control how many words appear in post excerpts throughout the theme.
 *
 * @since 1.0.0
 * @param int $length The current excerpt length.
 * @return int The modified excerpt length.
 *
 * @link https://developer.wordpress.org/reference/hooks/excerpt_length/
 */
function chronicle_journal_excerpt_length( $length ) {
	/**
	 * Set excerpt length to 25 words
	 * This provides a good balance between content preview and brevity
	 */
	return 25;
}
add_filter( 'excerpt_length', 'chronicle_journal_excerpt_length' );

/**
 * Customize the excerpt more string
 *
 * This function modifies the "read more" text that appears at the end of
 * post excerpts. It replaces the default "[...]" with a custom ellipsis.
 *
 * @since 1.0.0
 * @param string $more The current "more" text.
 * @return string The modified "more" text.
 *
 * @link https://developer.wordpress.org/reference/hooks/excerpt_more/
 */
function chronicle_journal_excerpt_more( $more ) {
	/**
	 * Replace default "[...]" with simple ellipsis
	 * Provides a cleaner, more minimal appearance
	 */
	return '...';
}
add_filter( 'excerpt_more', 'chronicle_journal_excerpt_more' );

/**
 * Customize the post author block
 *
 * This function modifies the post author block output to change the HTML structure
 * when a specific class is applied. It converts the author name from a paragraph
 * to an h1 element when the 'has-h1-font-size' class is present.
 *
 * @since 1.0.0
 * @param string $block_content The block content HTML.
 * @param array  $block         The block data array.
 * @return string The modified block content.
 *
 * @link https://developer.wordpress.org/reference/hooks/render_block_core-post-author/
 */
function chronicle_journal_post_author_block( $block_content, $block ) {
	/**
	 * Check if the block has the 'has-h1-font-size' class
	 * This allows for conditional HTML structure changes
	 */
	if ( isset( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'has-h1-font-size' ) !== false ) {

		/**
		 * Replace the author name wrapper from p to h1
		 * This provides better semantic structure for hero sections
		 */
		$block_content = preg_replace(
			'/<p class="wp-block-post-author__name">(.+?)<\/p>/',
			'<h1 class="wp-block-post-author__name">$1</h1>',
			$block_content
		);
	}

	return $block_content;
}
add_filter( 'render_block_core/post-author', 'chronicle_journal_post_author_block', 10, 2 );

/**
 * Set default featured image if the post does not provide it
 *
 * This function provides a fallback featured image for posts that don't have
 * a custom featured image set. It ensures all posts have a visual element
 * and maintains consistent design across the site.
 *
 * @since 1.0.0
 * @param string       $html              The post thumbnail HTML.
 * @param int          $post_id           The post ID.
 * @param int          $post_thumbnail_id The post thumbnail ID.
 * @param string|array $size              Requested image size.
 * @param array        $attr              Query string of attributes.
 * @return string The post thumbnail HTML or default image HTML.
 *
 * @link https://developer.wordpress.org/reference/hooks/post_thumbnail_html/
 */
function chronicle_journal_default_featured_image( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
	/**
	 * Check if the post has a featured image
	 * If no featured image is set, provide a default
	 */
	if ( empty( $html ) ) {
		/**
		 * Default featured image path
		 * Located in the theme's assets/images directory
		 */
		$default = get_template_directory_uri() . '/assets/images/featured-image-default.jpg';
		
		/**
		 * Generate alt text from post title
		 * Ensures accessibility and SEO compliance
		 */
		$alt = esc_attr( get_the_title( $post_id ) );
		
		/**
		 * Return default image HTML
		 * Includes proper escaping and WordPress post image class
		 */
		return '<img src="' . esc_url( $default ) . '" alt="' . $alt . '" class="wp-post-image" />';
	}
	
	/**
	 * Return original HTML if featured image exists
	 * Preserves existing featured images
	 */
	return $html;
}
add_filter( 'post_thumbnail_html', 'chronicle_journal_default_featured_image', 20, 5 );