<?php
/**
 * CommerceBird
 *
 * @package  CommerceBird
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class for All Product Data from Woo To Zoho
 *
 * @package  WooZo Inventory
 */

class CMBIRD_Image_ZI {

	private $config;
	public function __construct() {
		$this->config = array(
			'ProductZI' => array(
				'OID'    => get_option( 'cmbird_zoho_inventory_oid' ),
				'APIURL' => get_option( 'cmbird_zoho_inventory_url' ),
			),
		);
	}

	/**
	 * Attach image from zoho
	 *
	 * @param string $item_id - Item id for image details.
	 * @param string $item_name - Item name.
	 * @param string $image_name - Image name.
	 * @param string $post_id - Post id of product.
	 * @return integer | void
	 */
	public function cmbird_zi_get_image( $item_id, $item_name, $image_name, $post_id = null ) {
		// $fd = fopen( __DIR__ . '/cmbird_zi_get_image.txt', 'a+' );

		$attachment_id = $this->compare_image_by_title( $image_name );
		if ( $attachment_id && $post_id ) {
			set_post_thumbnail( $post_id, $attachment_id );
			update_post_meta( $attachment_id, '_wp_attachment_image_alt', $item_name );
			update_post_meta( $post_id, '_thumbnail_id', $attachment_id );
			wp_update_image_subsizes( $attachment_id );
			// Clean up only the specific downloaded image file.
			$upload_dir = wp_upload_dir();
			$local_path = $upload_dir['basedir'] . '/zoho_image/' . basename( $image_name );
			if ( file_exists( $local_path ) ) {
				wp_delete_file( $local_path );
			}
			return $attachment_id;
		} elseif ( $attachment_id ) {
			return $attachment_id;
		}

		$zoho_inventory_oid = $this->config['ProductZI']['OID'];
		$zoho_inventory_url = $this->config['ProductZI']['APIURL'];
		$url                = "{$zoho_inventory_url}inventory/v1/items/$item_id/image";
		$url               .= "?organization_id=$zoho_inventory_oid";

		$execute_curl_call_handle = new CMBIRD_API_Handler_Zoho();
		$image_url                = $execute_curl_call_handle->execute_curl_call_image_get( $url, $image_name );
		// log image url.
		// fwrite( $fd, "Fetched image URL: $image_url.\n" );
		if ( is_wp_error( $image_url ) || empty( $image_url ) ) {
			// log the error message and the item name.
			// $error_message = $image_url->get_error_message();
			// fwrite( $fd, "Error fetching image for item $item_name: $error_message\n" );
			return;
		}
		$upload_dir = wp_upload_dir();
		$local_path = $upload_dir['basedir'] . '/zoho_image/' . basename( $image_url );
		if ( file_exists( $local_path ) ) {

			// Sideload the image properly to WordPress uploads directory.
			require_once ABSPATH . 'wp-admin/includes/media.php';
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/image.php';

			// Prepare file array for sideloading.
			$file_array = array(
				'name'     => sanitize_file_name( $image_name ),
				'tmp_name' => $local_path,
			);

			// Sideload the image.
			$attach_id = media_handle_sideload( $file_array, $post_id, $item_name );

			if ( is_wp_error( $attach_id ) ) {
				// Clean up the temporary file on error.
				wp_delete_file( $local_path );
				return false;
			}

			// Set as featured image and update metadata.
			set_post_thumbnail( $post_id, $attach_id );
			update_post_meta( $attach_id, '_wp_attachment_image_alt', $item_name );
			update_post_meta( $post_id, '_thumbnail_id', $attach_id );
			wp_update_image_subsizes( $attach_id );

			// Clean up the temporary zoho_image file after successful sideload.
			wp_delete_file( $local_path );

			return $attach_id;
		} else {
			return;
		}
	}

	/**
	 * Compare the image with existing media library images based on titles.
	 *
	 * @param string $item_image The name of the image.
	 * @return int|bool The ID of the existing image if a match is found, or false if no match is found.
	 * @since 1.0.0
	 */
	protected function compare_image_by_title( $item_image ) {
		if ( empty( $item_image ) ) {
			return false;
		}

		$base_name    = pathinfo( $item_image, PATHINFO_FILENAME );
		$wp_sanitized = sanitize_title_with_dashes( $base_name );
		$hyphenated   = str_replace( array( ' ', '(', ')', '_', '.' ), '-', $base_name );
		$hyphenated   = preg_replace( '/-+/', '-', $hyphenated );
		$hyphenated   = trim( $hyphenated, '-' );

		$search_variations = array_unique(
			array(
				$base_name,
				strtolower( $base_name ),
				$wp_sanitized,
				$hyphenated,
				strtolower( $hyphenated ),
			)
		);

		global $wpdb;

		// Try exact title matches (case-insensitive).
		foreach ( $search_variations as $variation ) {
			$exact_match = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT p.ID FROM {$wpdb->posts} p WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND LOWER(p.post_title) = %s ORDER BY p.post_date DESC LIMIT 1",
					'image/%',
					strtolower( $variation )
				)
			);
			if ( $exact_match ) {
				return intval( $exact_match );
			}
		}

		// Try LIKE match for sanitized/slug variations in _wp_attached_file (any extension).
		foreach ( $search_variations as $variation ) {
			// Match: base, base-1, base-2, etc. (case-insensitive, any extension).
			$like_pattern   = $wpdb->esc_like( $variation ) . '%';
			$filename_match = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND pm.meta_key = '_wp_attached_file' AND (pm.meta_value LIKE %s OR pm.meta_value REGEXP %s) ORDER BY p.post_date DESC LIMIT 1",
					'image/%',
					'%' . $like_pattern . '.%',
					'/' . preg_quote( $variation, '/' ) . '(-[0-9]+)?\\.[a-zA-Z0-9]+$/'
				)
			);
			if ( $filename_match ) {
				return intval( $filename_match );
			}
		}

		// Try LIKE match for titles with -N suffix (case-insensitive).
		foreach ( $search_variations as $variation ) {
			$title_like_pattern = $wpdb->esc_like( $variation ) . '%';
			$title_match        = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT p.ID FROM {$wpdb->posts} p WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND (LOWER(p.post_title) LIKE %s OR LOWER(p.post_title) REGEXP %s) ORDER BY p.post_date DESC LIMIT 1",
					'image/%',
					strtolower( $title_like_pattern ),
					'^' . preg_quote( strtolower( $variation ), '/' ) . '(-[0-9]+)?$'
				)
			);
			if ( $title_match ) {
				return intval( $title_match );
			}
		}

		// Fallback: Try LIKE search for the raw $item_image (case-insensitive).
		$raw_filename_match = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND pm.meta_key = '_wp_attached_file' AND LOWER(pm.meta_value) LIKE %s ORDER BY p.post_date DESC LIMIT 1",
				'image/%',
				'%' . strtolower( $item_image ) . '%'
			)
		);
		if ( $raw_filename_match ) {
			return intval( $raw_filename_match );
		}

		return false;
	}
}
