<?php
/**
 * PostGate Icons Helper Class
 *
 * This file contains utility functions for icon management, including SVG icon
 * loading, base64 encoding for admin menu icons, inline SVG rendering, and
 * image asset loading for use throughout the PostGate plugin interface.
 *
 * Usage Examples:
 *
 *     // Get admin menu icon (base64 encoded SVG)
 *     $icon = PostGate_Icons::get_admin_menu_icon();
 *
 *     // Get inline SVG icon
 *     $svg = PostGate_Icons::get_svg_icon('lock', array('width' => 32, 'class' => 'my-icon'));
 *
 *     // Get image URL
 *     $logo_url = PostGate_Icons::get_image_url('postgate-logo.png');
 *
 *     // Get complete img tag
 *     $img = PostGate_Icons::get_image('banner.png', array('alt' => 'Banner', 'width' => 800));
 *
 *     // Get logo with automatic fallback
 *     $logo = PostGate_Icons::get_logo(array('return' => 'tag', 'width' => 200));
 *
 * @package PostGate
 * @subpackage Helpers
 * @since 1.0.0
 * @author QodeSphere
 * @license GPL-2.0+
 */

defined( 'ABSPATH' ) || exit;

/**
 * PostGate Icons Helper Class
 *
 * Provides utility functions for icon management within the PostGate plugin.
 * Handles SVG icon loading, base64 encoding for WordPress admin menu icons,
 * inline SVG rendering, and image asset loading for use in HTML templates.
 *
 * This class centralizes icon and image-related functionality including:
 * - Admin menu icon generation (base64-encoded SVG data URIs)
 * - Inline SVG rendering for HTML contexts
 * - SVG optimization and attribute manipulation
 * - PNG/JPG/WebP image loading from assets directory
 * - Logo and branding image retrieval
 *
 * All methods are static as they provide utility functionality without
 * requiring instance state or configuration.
 *
 * @since 1.0.0
 */
class PostGate_Icons {

	/**
	 * Get the PostGate admin menu icon as a base64-encoded SVG data URI.
	 *
	 * Loads the main PostGate logo SVG from the assets/icons directory,
	 * encodes it to base64, and returns it as a data URI suitable for
	 * use in WordPress add_menu_page() function.
	 *
	 * Falls back to 'dashicons-lock' if the SVG file cannot be loaded.
	 *
	 * @since 1.0.0
	 * @return string Base64-encoded SVG data URI for use in add_menu_page().
	 */
	public static function get_admin_menu_icon() {
		$svg_path = POSTGATE_PATH . 'assets/icons/postgate-icon.svg';

		if ( ! file_exists( $svg_path ) ) {
			// Fallback to dashicon if SVG doesn't exist
			return 'dashicons-lock';
		}

		// Read SVG file
		$svg_content = file_get_contents( $svg_path );

		if ( false === $svg_content ) {
			return 'dashicons-lock';
		}

		// Encode to base64
		$base64 = base64_encode( $svg_content );

		// Return as data URI
		return 'data:image/svg+xml;base64,' . $base64;
	}

	/**
	 * Get SVG icon markup for use in HTML.
	 *
	 * Loads an SVG file from the assets/icons directory and returns it
	 * as inline HTML with optional custom attributes (width, height, class).
	 *
	 * Useful for rendering icons in admin pages, templates, or other
	 * HTML contexts where inline SVG is preferred over data URIs.
	 *
	 * @since 1.0.0
	 * @param string $icon_name Icon filename without extension.
	 * @param array  $args      Optional. Icon attributes (width, height, class). Default empty array.
	 * @return string SVG icon markup, or empty string if file not found.
	 */
	public static function get_svg_icon( $icon_name, $args = array() ) {
		$defaults = array(
			'width' => 24,
			'height' => 24,
			'class' => '',
		);

		$args = wp_parse_args( $args, $defaults );

		$svg_path = POSTGATE_PATH . "assets/icons/{$icon_name}.svg";

		if ( ! file_exists( $svg_path ) ) {
			return '';
		}

		$svg_content = file_get_contents( $svg_path );

		if ( false === $svg_content ) {
			return '';
		}

		// Add custom class if provided
		if ( ! empty( $args['class'] ) ) {
			$svg_content = str_replace( '<svg', '<svg class="' . esc_attr( $args['class'] ) . '"', $svg_content );
		}

		// Override width/height if different from default
		$svg_content = preg_replace( '/width="[^"]*"/', 'width="' . $args['width'] . '"', $svg_content );
		$svg_content = preg_replace( '/height="[^"]*"/', 'height="' . $args['height'] . '"', $svg_content );

		return $svg_content;
	}

	/**
	 * Get inline SVG for React/JS usage.
	 *
	 * Returns SVG content without XML declaration for embedding in JSX
	 * or JavaScript contexts. The XML declaration is removed to ensure
	 * compatibility with React and other JS frameworks.
	 *
	 * @since 1.0.0
	 * @param string $icon_name Icon filename without extension.
	 * @return string SVG markup without XML declaration, or empty string if not found.
	 */
	public static function get_inline_svg( $icon_name ) {
		$svg_path = POSTGATE_PATH . "assets/icons/{$icon_name}.svg";

		if ( ! file_exists( $svg_path ) ) {
			return '';
		}

		$svg_content = file_get_contents( $svg_path );

		// Remove XML declaration
		$svg_content = preg_replace( '/<\?xml.*?\?>/', '', $svg_content );

		return trim( $svg_content );
	}

	/**
	 * Get image URL from assets/images directory.
	 *
	 * Returns the full URL to an image file in the assets/images directory.
	 * Supports common image formats: PNG, JPG, JPEG, GIF, WebP, SVG.
	 *
	 * Useful for loading logos, banners, and other raster images in admin
	 * pages or templates where you need the URL for use in img src attributes.
	 *
	 * @since 1.0.0
	 * @param string $image_name Image filename with extension (e.g., 'logo.png', 'banner.jpg').
	 * @return string Image URL, or empty string if file not found.
	 */
	public static function get_image_url( $image_name ) {
		$image_path = POSTGATE_PATH . "assets/images/{$image_name}";

		if ( ! file_exists( $image_path ) ) {
			return '';
		}

		return POSTGATE_URL . "assets/images/{$image_name}";
	}

	/**
	 * Get complete image tag markup for use in HTML.
	 *
	 * Returns a complete HTML <img> tag with the image URL and optional
	 * attributes such as alt text, width, height, class, and additional
	 * HTML attributes.
	 *
	 * Automatically generates proper WordPress-style image markup with
	 * escaped attributes for security.
	 *
	 * @since 1.0.0
	 * @param string $image_name Image filename with extension (e.g., 'logo.png').
	 * @param array  $args       Optional. Image attributes. Default empty array.
	 *                           Accepts:
	 *                           - 'alt' (string) Alt text for accessibility. Default empty.
	 *                           - 'width' (int) Image width in pixels. Default null.
	 *                           - 'height' (int) Image height in pixels. Default null.
	 *                           - 'class' (string) CSS classes. Default empty.
	 *                           - 'id' (string) Element ID. Default empty.
	 *                           - 'loading' (string) Loading attribute ('lazy', 'eager'). Default 'lazy'.
	 *                           - 'title' (string) Title attribute. Default empty.
	 * @return string Complete <img> tag markup, or empty string if image not found.
	 */
	public static function get_image( $image_name, $args = array() ) {
		$image_url = self::get_image_url( $image_name );

		if ( empty( $image_url ) ) {
			return '';
		}

		$defaults = array(
			'alt' => '',
			'width' => null,
			'height' => null,
			'class' => '',
			'id' => '',
			'loading' => 'lazy',
			'title' => '',
		);

		$args = wp_parse_args( $args, $defaults );

		// Build img tag
		$attributes = array(
			sprintf( 'src="%s"', esc_url( $image_url ) ),
			sprintf( 'alt="%s"', esc_attr( $args['alt'] ) ),
		);

		if ( ! empty( $args['width'] ) ) {
			$attributes[] = sprintf( 'width="%d"', absint( $args['width'] ) );
		}

		if ( ! empty( $args['height'] ) ) {
			$attributes[] = sprintf( 'height="%d"', absint( $args['height'] ) );
		}

		if ( ! empty( $args['class'] ) ) {
			$attributes[] = sprintf( 'class="%s"', esc_attr( $args['class'] ) );
		}

		if ( ! empty( $args['id'] ) ) {
			$attributes[] = sprintf( 'id="%s"', esc_attr( $args['id'] ) );
		}

		if ( ! empty( $args['loading'] ) ) {
			$attributes[] = sprintf( 'loading="%s"', esc_attr( $args['loading'] ) );
		}

		if ( ! empty( $args['title'] ) ) {
			$attributes[] = sprintf( 'title="%s"', esc_attr( $args['title'] ) );
		}

		return sprintf( '<img %s />', implode( ' ', $attributes ) );
	}

	/**
	 * Get PostGate logo image.
	 *
	 * Convenience method to retrieve the PostGate logo specifically.
	 * Falls back through multiple logo variations if the primary logo
	 * is not found (e.g., logo.png → logo.svg → logo.jpg).
	 *
	 * Optionally returns just the URL or a complete <img> tag.
	 *
	 * @since 1.0.0
	 * @param array $args Optional. Image attributes and options. Default empty array.
	 *                    Accepts all parameters from get_image() plus:
	 *                    - 'return' (string) Return type: 'url' or 'tag'. Default 'url'.
	 * @return string Logo URL or <img> tag markup, or empty string if not found.
	 */
	public static function get_logo( $args = array() ) {
		$defaults = array(
			'return' => 'url',
			'alt' => 'PostGate',
		);

		$args = wp_parse_args( $args, $defaults );

		// Try different logo variations in order of preference
		$logo_variations = array(
			'postgate-logo.png',
			'postgate-logo.svg',
			'logo.png',
			'logo.svg',
			'postgate-logo.jpg',
			'logo.jpg',
		);

		$logo_url = '';
		$found_logo = '';

		foreach ( $logo_variations as $variation ) {
			$url = self::get_image_url( $variation );
			if ( ! empty( $url ) ) {
				$logo_url = $url;
				$found_logo = $variation;
				break;
			}
		}

		if ( empty( $logo_url ) ) {
			return '';
		}

		// Return URL or complete img tag based on 'return' argument
		if ( 'url' === $args['return'] ) {
			return $logo_url;
		}

		// Remove 'return' from args before passing to get_image()
		unset( $args['return'] );

		return self::get_image( $found_logo, $args );
	}
}
