<?php
/**
 * Image Helper class.
 *
 * Resolves the best available thumbnail URL for a post.
 * Replaces timthumb.php and get-the-image.php.
 *
 * @package IGIT_RPWT
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class IGIT_RPWT_Image_Helper {

	/**
	 * Register the plugin's custom thumbnail image size.
	 * Hooked to after_setup_theme so themes can override.
	 */
	public static function register_image_size() {
		add_image_size( 'igit-rpwt-thumb', 300, 200, true );
	}

	/**
	 * Return the URL of the best available image for $post_id.
	 *
	 * Priority:
	 *  1. Post featured image (post thumbnail)
	 *  2. First image attached to the post
	 *  3. First <img> src found in post content
	 *  4. Configured default_image setting
	 *  5. Bundled noimage.gif
	 *
	 * @param int    $post_id
	 * @param string $size  WordPress image size name.
	 * @return string  Absolute image URL (never empty).
	 */
	public static function get_image_url( $post_id, $size = 'igit-rpwt-thumb' ) {
		// 1. Featured image.
		if ( has_post_thumbnail( $post_id ) ) {
			$url = get_the_post_thumbnail_url( $post_id, $size );
			if ( $url ) {
				return $url;
			}
		}

		// 2. First attached image.
		$attachments = get_posts( array(
			'post_type'      => 'attachment',
			'post_mime_type' => 'image',
			'post_parent'    => $post_id,
			'posts_per_page' => 1,
			'orderby'        => 'menu_order',
			'order'          => 'ASC',
			'fields'         => 'ids',
		) );

		if ( ! empty( $attachments ) ) {
			$url = wp_get_attachment_image_url( $attachments[0], $size );
			if ( $url ) {
				return $url;
			}
		}

		// 3. Scan post content for <img> tags.
		$post = get_post( $post_id );
		if ( $post ) {
			preg_match( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post->post_content, $matches );
			if ( ! empty( $matches[1] ) ) {
				$img_url = $matches[1];
				// Only use images hosted on this site.
				if ( strpos( $img_url, home_url() ) !== false ) {
					return esc_url( $img_url );
				}
			}
		}

		// 4. Admin-configured default image.
		$default = IGIT_RPWT_Settings::get( 'default_image' );
		if ( ! empty( $default ) ) {
			return esc_url( $default );
		}

		// 5. Bundled fallback.
		return IGIT_RPWT_PLUGIN_URL . 'images/noimage.gif';
	}
}
