<?php
/**
 * Handles article assets.
 *
 * @package flo-sync
 */

namespace NMFS\Sync\Items\Articles;

use Exception;
use NMFS\Shared;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Main_API;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Helpers\File_System_Helper;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;

defined( 'ABSPATH' ) || exit;

/**
 * Class Article_Assets
 */
class Article_Assets {

	/**
	 * Upload images for product.
	 *
	 * @param int     $product_id WC Product ID.
	 * @param array[] $images     Array of images.
	 *
	 * @return void
	 */
	public static function upload_images( int $product_id, array $images ): void {
		/**
		 * TODO: Stop creating multiple images a for products which is stop force sync creating multiple image generated */
		$image_gallery = array();
		foreach ( $images as $image ) {
			$image_url     = $image['URL']; // Define the image URL here.
			$image_name    = $image['Name'];
			$image_type    = $image['ContentType'];
			$feature_image = $image['IsMainFile'];
			$tmp           = get_temp_dir() . $image_name; // temp folder locations and filename.

			// If the file is already imported, skip download.
			$already_exists = get_posts(
				array(
					'post_type'           => 'attachment',
					'posts_per_page'      => 1,
					'ignore_sticky_posts' => true,
					'meta_query'          => array(
						'relation' => 'AND',
						array(
							'key'   => Articles::META_KEY_IMAGE_ID,
							'value' => $image['Id'],
						),
						array(
							'key'   => Articles::META_KEY_IMAGE_NAME,
							'value' => $image['Name'],
						),
					),
					'fields'              => 'ids',
				)
			);

			if ( ! empty( $already_exists ) ) {
				if ( $feature_image ) {
					set_post_thumbnail( $product_id, $already_exists[0] );
				} else {
					$image_gallery[] = $already_exists[0];
				}

				wp_update_post(
					array(
						'ID'           => $already_exists[0],
						'post_content' => $image['Description'],
					)
				);
				continue;
			}

			$compatible_types = array( 'image/jpeg', 'image/png', 'image/gif' );
			if ( ! in_array( $image_type, $compatible_types, true ) ) {
				Shared::instance()->logger->log(
					'sync',
					'Image type invalid, skipping download of image',
					array(
						'image_id' => $image['Id'],
						'type'     => $image_type,
						'image'    => $image,
					),
					Log_Level_Enum::WARNING
				);
				continue;
			}
			$api        = new Main_API();
			$image_data = $api->get_image_file( $image_url, $image_type );

			if ( $image_data ) {
				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 file to temp location.
				$tmp_dl = File_System_Helper::put_contents( $tmp, $image_data );

				// Set variables for storage.
				$file_array['name']     = $image_name;
				$file_array['tmp_name'] = $tmp;

				if ( is_wp_error( $tmp_dl ) ) {
					try {
						wp_delete_file( $file_array['tmp_name'] );
					} catch ( Exception $e ) {
						Shared::instance()->logger->log(
							'sync',
							'Error on delete image from temp folder',
							array(
								'file' => $file_array['tmp_name'],
							),
							Log_Level_Enum::ERROR
						);
					}

					Shared::instance()->logger->log(
						'sync',
						'Error on download image from url',
						array(
							'url' => $image_url,
						),
						Log_Level_Enum::ERROR
					);
					continue;
				}

				$image_id = media_handle_sideload(
					$file_array,
					$product_id,
					$image_name,
					array(
						'post_content' => $image['Description'],
					)
				);

				if ( is_wp_error( $image_id ) ) {
					try {
						wp_delete_file( $file_array['tmp_name'] );
					} catch ( Exception $e ) {
						Shared::instance()->logger->log(
							'sync',
							'Error on delete image from temp folder',
							array(
								'file' => $file_array['tmp_name'],
							),
							Log_Level_Enum::ERROR
						);
					}
					Shared::instance()->logger->log(
						'sync',
						'Error on upload to WordPress image',
						array(
							'error' => $image_id->get_error_message(),
						),
						Log_Level_Enum::ERROR
					);
					continue;
				} else {
					update_post_meta( $image_id, Articles::META_KEY_IMAGE_ID, $image['Id'] );
					update_post_meta( $image_id, Articles::META_KEY_IMAGE_NAME, $image['Name'] );
				}

				if ( $feature_image ) {
					set_post_thumbnail( $product_id, $image_id );
				} else {
					$image_gallery[] = $image_id;
				}
				unset( $image_id );
			} else {
				Shared::instance()->logger->log(
					'sync',
					'Error on download image from url',
					array(
						'note' => 'Might be due article name containing spaces.EX: /articles/Article+test/',
						'url'  => $image_url,
					),
					Log_Level_Enum::ERROR
				);
			}
		}
		if ( ! empty( $image_gallery ) ) {
			update_post_meta( $product_id, '_product_image_gallery', implode( ',', $image_gallery ) );
		}
	}
}
