<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register term meta for categories to allow custom story avatars.
 *
 * @since      1.0.0
 * @package    Storyposts
 * @subpackage Storyposts/includes/meta
 */
class Storyposts_Category_Meta {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		add_action( 'storyposts_cmb2_admin_init', array( $this, 'register_term_metabox' ) );
	}

	/**
	 * Register the term meta box using CMB2.
	 *
	 * @since    1.0.0
	 */
	public function register_term_metabox() {

		$prefix = '_stpo_';

		/**
		 * Category Story Settings
		 */
		$cmb = new_storyposts_cmb2_box( array(
			'id'               => $prefix . 'category_meta',
			'title'            => esc_html__( 'StoryPosts Settings', 'storyposts' ),
			'object_types'     => array( 'term' ),
			'taxonomies'       => array( 'category' ),
			'new_term_section' => true,
		) );

		$cmb->add_field( array(
			'name' => esc_html__( 'Category Story Image', 'storyposts' ),
			'desc' => esc_html__( 'Custom avatar for this category in the story tray. Fallback: Latest post featured image.', 'storyposts' ),
			'id'   => $prefix . 'category_image',
			'type' => 'file',
			'options' => array(
				'url' => false,
			),
			'text' => array(
				'add_upload_file_text' => esc_html__( 'Add Image', 'storyposts' ),
			),
			'query_args' => array(
				'type' => 'image',
			),
			'preview_size' => 'thumbnail',
		) );
	}

	/**
	 * Helper to get category image URL with fallbacks.
	 * 
	 * 1. Custom category image
	 * 2. Latest post featured image
	 * 3. Default placeholder
	 */
	public static function get_category_image_url( $term_id ) {
		$term = get_term( $term_id );
		$taxonomy = $term ? $term->taxonomy : 'category';

		// 1. Handle WooCommerce product categories
		if ( 'product_cat' === $taxonomy ) {
			$thumbnail_id = get_term_meta( $term_id, 'thumbnail_id', true );
			if ( $thumbnail_id ) {
				$url = wp_get_attachment_image_url( $thumbnail_id, 'thumbnail' );
				if ( $url ) {
					return $url;
				}
			}
		}

		// 2. Try StoryPosts custom key
		$image_data = get_term_meta( $term_id, '_stpo_category_image', true );
		
		// 3. Try old key as fallback
		if ( ! $image_data ) {
			$image_data = get_term_meta( $term_id, '_stpo_category_id', true );
		}

		if ( $image_data ) {
			// Handle ID
			if ( is_numeric( $image_data ) ) {
				$url = wp_get_attachment_image_url( $image_data, 'thumbnail' );
				if ( $url ) {
					return $url;
				}
			}
			// Handle URL (if saved as string)
			if ( is_string( $image_data ) && ( strpos( $image_data, 'http' ) === 0 || strpos( $image_data, '/' ) === 0 ) ) {
				return $image_data;
			}
		}

		// Fallback to latest post featured image
		$query_args = array(
			'posts_per_page' => 1,
			'post_status'    => 'publish',
			'meta_key'       => '_thumbnail_id',
		);

		if ( 'product_cat' === $taxonomy ) {
			$query_args['post_type'] = 'product';
			$query_args['tax_query'] = array(
				array(
					'taxonomy' => 'product_cat',
					'field'    => 'term_id',
					'terms'    => $term_id,
				),
			);
		} else {
			$query_args['post_type'] = 'post';
			$query_args['category']  = $term_id;
		}

		$latest_posts = get_posts( $query_args );

		if ( ! empty( $latest_posts ) ) {
			return get_the_post_thumbnail_url( $latest_posts[0]->ID, 'thumbnail' );
		}

		return STORYPOSTS_URL . 'public/images/placeholder.png';
	}
}
