<?php

namespace wpsolr\core\classes\utilities;

use wpsolr\core\classes\WPSOLR_Events;
use wpsolr\core\classes\WpSolrSchema;

trait WPSOLR_Post_Type_Embedded_File {

	/**
	 * Send files as url or content
	 */
	static protected $FILE_SEND_AS_URL = 'source';
	static protected $FILE_SEND_AS_CONTENT = 'content';

	/**
	 * @param string $image_src
	 *
	 * @return bool
	 */
	protected function _get_is_image_format_supported( $image_src ) {
		return true;
	}

	/**
	 * @param string $send_file_as
	 * @param string $url
	 * @param $home_url
	 *
	 * @return array
	 */
	protected function _get_file_content_or_source( $send_file_as, $url, $home_url ) {

		if ( str_starts_with( $url, '/' ) ) {
			// Internal url without the domain: add it to prevent errors later while getting the file content
			$url = sprintf( '%s%s', $home_url, $url );
		}

		return [ $send_file_as => ( static::$FILE_SEND_AS_CONTENT === $send_file_as ) ? file_get_contents( $url ) : $url ];
	}

	/**
	 * Extract all images from a document before an update: featured, embedded ...
	 *
	 * @param array $document_for_update
	 *
	 * @return array
	 */
	protected function _extract_embedded_files_from_document( $document_for_update, $params ) {

		$images   = [];
		$home_url = home_url();

		if ( ( $params['is_attachment_image'] ?? false ) &&
		     ( $image_src = wp_get_attachment_image_src( $document_for_update[ WpSolrSchema::_FIELD_NAME_PID ], 'full' ) ) ) {
			// Attachment
			if ( $this->_get_is_image_format_supported( $image_src[0] ) ) {
				try {
					$images[] = $this->_get_file_content_or_source( $params['internal_image_mode'], $image_src[0], $home_url );
				} catch ( \Exception $e ) {
					// Skip error, continue
				}
			}

		} else {
			// Extract images from the post type

			// Featured image
			if ( ( $params['is_featured_image'] ?? false ) &&
			     ( $image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $document_for_update[ WpSolrSchema::_FIELD_NAME_PID ] ), 'full' ) ) ) {
				if ( $this->_get_is_image_format_supported( $image_src[0] ) ) {
					try {
						$images[] = $this->_get_file_content_or_source( $params['internal_image_mode'], $image_src[0], $home_url );
					} catch ( \Exception $e ) {
						// Skip error, continue
					}
				}
			}

			// Images embedded in HTML
			// Use post content, because it is not stripped
			if ( ( ( $params['is_embedded_image'] ?? false ) &&
			       ( $post = get_post( $document_for_update[ WpSolrSchema::_FIELD_NAME_PID ] ) ) &&
			       preg_match_all( '/src="([^"]*)"/', $post->post_content, $matches ) ) ) {
				foreach ( $matches[1] as $image_src ) {
					if ( $this->_get_is_image_format_supported( $image_src ) ) {
						$is_internal_url = $this->_is_url_internal( $image_src, $home_url );
						try {
							if ( ! ( $is_internal_url ) &&
							     ! ( $params['external_file_mode'] ?? false ) ) {
								// External url not wanted
								continue;
							}
							$images[] = $this->_get_file_content_or_source( $is_internal_url ? $params['internal_image_mode'] : $params['external_image_mode'], $image_src, $home_url );
						} catch ( \Exception $e ) {
							// Skip error, continue
						}
					}
				}
			}

			// Files embedded in HTML
			// Use post content, because it is not stripped
			if ( ( ( $params['is_embedded_file'] ?? false ) &&
			       ( $post = get_post( $document_for_update[ WpSolrSchema::_FIELD_NAME_PID ] ) ) &&
			       preg_match_all( '/<a\s[^>]*href=["\']([^"\']+)["\']/i', $post->post_content, $matches ) ) ) {
				foreach ( $matches[1] as $image_src ) {
					if ( $this->_get_is_image_format_supported( $image_src ) ) {
						$is_internal_url = $this->_is_url_internal( $image_src, $home_url );
						try {
							if ( ! ( $is_internal_url ) &&
							     ! ( $params['external_file_mode'] ?? false ) ) {
								// External url not wanted
								continue;
							}
							$images[] = $this->_get_file_content_or_source( $is_internal_url ? $params['internal_file_mode'] : $params['external_file_mode'], $image_src, $home_url );
						} catch ( \Exception $e ) {
							// Skip error, continue
						}
					}
				}
			}


		}

		/**
		 * Let other plugins add extra images.
		 * For instance, WooCommerce images gallery.
		 */
		$extra_images = apply_filters( WPSOLR_Events::WPSOLR_FILTER_AI_POST_TYPE_IMAGES_URLS, [], $document_for_update[ WpSolrSchema::_FIELD_NAME_PID ] );
		foreach ( $extra_images as $image_src ) {
			if ( $this->_get_is_image_format_supported( $image_src ) ) {
				$is_internal_url = $this->_is_url_internal( $image_src, home_url() );
				try {
					$images[] = $this->_get_file_content_or_source( $is_internal_url ? $params['internal_image_mode'] : $params['external_image_mode'], $image_src, $home_url );
				} catch ( \Exception $e ) {
					// Skip error, continue
				}
			}
		}

		return $images;
	}

	/**
	 * @param string $image_src
	 * @param string|null $home_url
	 *
	 * @return bool
	 */
	protected function _is_url_internal( string $image_src, ?string $home_url ): bool {
		return ( str_starts_with( $image_src, '/' ) || str_starts_with( $image_src, $home_url ) );
	}

}