<?php
/**
 * Image Utilities
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Utils;

/**
 * Provides image-related utility functions
 */
class Image {

	/**
	 * Get image URL from attachment ID
	 *
	 * @param int    $attachment_id Attachment ID
	 * @param string $size Image size
	 * @return string|false Image URL or false on failure
	 */
	public static function get_image_url( $attachment_id, $size = 'full' ) {
		if ( empty( $attachment_id ) ) {
			return false;
		}

		$image_url = wp_get_attachment_image_url( $attachment_id, $size );

		if ( ! $image_url ) {
			return false;
		}

		return $image_url;
	}

	/**
	 * Get image alt text from attachment ID
	 *
	 * @param int $attachment_id Attachment ID
	 * @return string Alt text
	 */
	public static function get_image_alt( $attachment_id ) {
		if ( empty( $attachment_id ) ) {
			return '';
		}

		$alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );

		return is_string( $alt ) ? $alt : '';
	}

	/**
	 * Validate image URL
	 *
	 * @param string $url Image URL
	 * @return bool
	 */
	public static function is_valid_image_url( $url ) {
		if ( empty( $url ) ) {
			return false;
		}

		$url = esc_url_raw( $url );

		if ( empty( $url ) ) {
			return false;
		}

		// Check if it's a valid URL
		if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
			return false;
		}

		// Check for valid image extensions
		$allowed_extensions = array( 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg' );
		$path               = wp_parse_url( $url, PHP_URL_PATH );

		if ( ! $path ) {
			return false;
		}

		$extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );

		return in_array( $extension, $allowed_extensions, true );
	}

	/**
	 * Generate responsive image attributes
	 *
	 * @param int    $attachment_id Attachment ID
	 * @param string $size Image size
	 * @return array Image attributes
	 */
	public static function get_responsive_image_attrs( $attachment_id, $size = 'full' ) {
		if ( empty( $attachment_id ) ) {
			return array();
		}

		$src = self::get_image_url( $attachment_id, $size );

		if ( ! $src ) {
			return array();
		}

		$attrs = array(
			'src' => $src,
			'alt' => self::get_image_alt( $attachment_id ),
		);

		// Add srcset if available
		$srcset = wp_get_attachment_image_srcset( $attachment_id, $size );
		if ( $srcset ) {
			$attrs['srcset'] = $srcset;
		}

		// Add sizes if available
		$sizes = wp_get_attachment_image_sizes( $attachment_id, $size );
		if ( $sizes ) {
			$attrs['sizes'] = $sizes;
		}

		return $attrs;
	}
}
