<?php
/**
 * Media library helpers for AI-generated images.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class Media {

	/**
	 * Save raw image bytes into the media library and optionally attach to a product.
	 *
	 * @param string $bytes       Raw binary image data.
	 * @param string $mime        Mime type (image/png, image/jpeg, image/webp).
	 * @param int    $product_id  Parent post id (0 for none).
	 * @param string $filename    Optional filename.
	 * @param string $alt_text    Optional alt text.
	 * @return int|\WP_Error Attachment ID on success.
	 */
	public static function sideload_bytes( $bytes, $mime, $product_id = 0, $filename = '', $alt_text = '' ) {
		if ( empty( $bytes ) ) {
			return new \WP_Error( 'cpais_media_empty', __( 'No image data.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$ext_map = array(
			'image/png'  => 'png',
			'image/jpeg' => 'jpg',
			'image/jpg'  => 'jpg',
			'image/webp' => 'webp',
			'image/gif'  => 'gif',
		);
		$mime = strtolower( trim( explode( ';', $mime )[0] ?? 'image/png' ) );
		$ext  = $ext_map[ $mime ] ?? 'png';

		if ( '' === $filename ) {
			$filename = 'cpais-' . gmdate( 'Ymd-His' ) . '-' . wp_generate_password( 6, false, false );
		}
		$filename = sanitize_file_name( $filename . '.' . $ext );

		$upload = wp_upload_bits( $filename, null, $bytes );
		if ( ! empty( $upload['error'] ) ) {
			return new \WP_Error( 'cpais_upload_failed', $upload['error'] );
		}

		$file = $upload['file'];

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

		$attachment = array(
			'post_mime_type' => $mime,
			'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		);

		$attach_id = wp_insert_attachment( $attachment, $file, $product_id );
		if ( is_wp_error( $attach_id ) ) {
			return $attach_id;
		}

		$metadata = wp_generate_attachment_metadata( $attach_id, $file );
		wp_update_attachment_metadata( $attach_id, $metadata );

		if ( '' !== $alt_text ) {
			update_post_meta( $attach_id, '_wp_attachment_image_alt', sanitize_text_field( $alt_text ) );
		}

		return $attach_id;
	}

	/**
	 * Remove the background from an existing media-library image, save the
	 * transparent PNG result as a new attachment, and optionally attach it
	 * to a product.
	 *
	 * @param int    $source_attachment_id Existing attachment to process.
	 * @param string $api_key              Replicate API token.
	 * @param string $model                Replicate model (owner/name).
	 * @param int    $product_id           Optional product to attach the new image to.
	 * @param string $attach_as            'featured' or 'gallery' (or empty to skip).
	 * @return array|\WP_Error  { attachment_id, url, source_url } on success.
	 */
	public static function remove_background( $source_attachment_id, $api_key, $model = '851-labs/background-remover', $product_id = 0, $attach_as = '' ) {
		$source_attachment_id = absint( $source_attachment_id );
		if ( ! $source_attachment_id || 'attachment' !== get_post_type( $source_attachment_id ) ) {
			return new \WP_Error( 'cpais_invalid_attachment', __( 'Source image not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		if ( '' === (string) $api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Replicate API token is required for background removal.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 400 ) );
		}

		$source_url = wp_get_attachment_url( $source_attachment_id );
		if ( ! $source_url ) {
			return new \WP_Error( 'cpais_no_source_url', __( 'Could not resolve source image URL.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 500 ) );
		}

		$provider = new \CatalogPilot\AiStudio\Providers\Image_Replicate_Provider( $api_key, '' );
		$result   = $provider->remove_background( $source_url, $model );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$source_title = get_the_title( $source_attachment_id );
		$base         = '' !== $source_title ? sanitize_file_name( $source_title ) : 'image';
		$filename     = $base . '-nobg-' . wp_generate_password( 6, false, false );

		$new_id = self::sideload_bytes(
			$result['bytes'],
			$result['mime'],
			absint( $product_id ),
			$filename,
			get_post_meta( $source_attachment_id, '_wp_attachment_image_alt', true )
		);
		if ( is_wp_error( $new_id ) ) {
			return $new_id;
		}

		if ( $product_id && in_array( $attach_as, array( 'featured', 'gallery' ), true ) ) {
			self::attach_to_product( $new_id, $product_id, $attach_as );
		}

		return array(
			'attachment_id' => (int) $new_id,
			'url'           => wp_get_attachment_url( $new_id ),
			'source_url'    => $source_url,
		);
	}

	public static function attach_to_product( $attach_id, $product_id, $as = 'featured' ) {
		$product_id = absint( $product_id );
		$attach_id  = absint( $attach_id );
		if ( ! $product_id || ! $attach_id ) {
			return false;
		}

		if ( 'featured' === $as ) {
			set_post_thumbnail( $product_id, $attach_id );
			return (int) get_post_meta( $product_id, '_thumbnail_id', true ) === $attach_id;
		}

		if ( 'gallery' === $as ) {
			$gallery = get_post_meta( $product_id, '_product_image_gallery', true );
			$ids     = array_filter( array_map( 'absint', explode( ',', (string) $gallery ) ) );
			if ( ! in_array( $attach_id, $ids, true ) ) {
				$ids[] = $attach_id;
				update_post_meta( $product_id, '_product_image_gallery', implode( ',', $ids ) );
			}
			return true;
		}

		return false;
	}
}
