<?php

namespace SugarCalendarBookings\Migration;

/**
 * Image Migration Handler.
 *
 * Handles image migration from Amelia to Sugar Calendar Bookings.
 * Reuses existing WordPress media library attachments when possible.
 *
 * @since 1.3.0
 */
class ImageMigrationHandler {

	/**
	 * Migrate an image from URL to WordPress media library.
	 *
	 * If the image already exists in the media library, returns that attachment ID.
	 * Otherwise, downloads and uploads the image to create a new attachment.
	 *
	 * @since 1.3.0
	 *
	 * @param string $image_url   Image URL.
	 * @param string $entity_name Entity name for image title (service/employee name).
	 *
	 * @return int|false Attachment ID on success, false on failure.
	 */
	public function migrate_image( $image_url, $entity_name = '' ) {

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

		// Check if image URL is valid.
		if ( ! filter_var( $image_url, FILTER_VALIDATE_URL ) ) {
			return false;
		}

		// Find existing attachment in media library by URL.
		$attachment_id = $this->find_attachment_by_guid( $image_url );

		if ( $attachment_id ) {
			return $attachment_id;
		}

		// Fallback: Download and upload image (for external URLs).
		return $this->download_and_upload_image( $image_url, $entity_name );
	}

	/**
	 * Find attachment by URL.
	 *
	 * Uses WordPress native attachment_url_to_postid() which has built-in caching.
	 *
	 * @since 1.3.0
	 *
	 * @param string $url Image URL.
	 *
	 * @return int|false Attachment ID or false.
	 */
	private function find_attachment_by_guid( $url ) {

		$attachment_id = attachment_url_to_postid( $url );

		return $attachment_id ? (int) $attachment_id : false;
	}

	/**
	 * Download and upload image to media library.
	 *
	 * @since 1.3.0
	 *
	 * @param string $image_url   Image URL.
	 * @param string $entity_name Entity name for filename.
	 *
	 * @return int|false Attachment ID on success, false on failure.
	 */
	private function download_and_upload_image( $image_url, $entity_name ) {

		require_once ABSPATH . 'wp-admin/includes/media.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/image.php';

		// Download image.
		$temp_file = download_url( $image_url );

		if ( is_wp_error( $temp_file ) ) {
			return false;
		}

		// Prepare file array.
		$file_array = [
			'name'     => $this->generate_filename( $image_url, $entity_name ),
			'tmp_name' => $temp_file,
		];

		// Upload to media library.
		$attachment_id = media_handle_sideload( $file_array, 0 );

		// Clean up temp file on error.
		if ( is_wp_error( $attachment_id ) ) {
			wp_delete_file( $temp_file );

			return false;
		}

		return $attachment_id;
	}

	/**
	 * Generate filename from URL and entity name.
	 *
	 * @since 1.3.0
	 *
	 * @param string $url         Image URL.
	 * @param string $entity_name Entity name.
	 *
	 * @return string Filename.
	 */
	private function generate_filename( $url, $entity_name ) {

		$path_parts = pathinfo( wp_parse_url( $url, PHP_URL_PATH ) );
		$extension  = isset( $path_parts['extension'] ) ? $path_parts['extension'] : 'jpg';

		if ( ! empty( $entity_name ) ) {
			$filename = sanitize_file_name( $entity_name );

			return $filename . '.' . $extension;
		}

		return isset( $path_parts['basename'] ) ? $path_parts['basename'] : 'image.' . $extension;
	}
}
