<?php
defined('ABSPATH') || exit;

/**
 * Class Storyposts_Get_Collection_Stories
 *
 * Handles retrieving collection stories for the StoryPosts feature.
 * Collections are admin-created albums containing multiple stories.
 *
 * @since      1.0.0
 * @package    Storyposts
 * @subpackage Storyposts/includes/collection-stories
 */
class Storyposts_Get_Collection_Stories {

	/**
	 * Register AJAX actions.
	 */
	public function __construct() {
		add_action( 'wp_ajax_storyposts_get_collection_stories', [ $this, 'handle' ] );
		add_action( 'wp_ajax_nopriv_storyposts_get_collection_stories', [ $this, 'handle' ] );
	}

	/**
	 * Handles fetching collections and their stories.
	 *
	 * Returns collections ordered by display order, with their stories.
	 */
	public function handle() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'storyposts_fetch_stories' ) ) {
			wp_send_json_error( 'Invalid nonce' );
		}

		$offset = absint( $_POST['offset'] ?? 0 );
		$limit  = absint( $_POST['limit'] ?? Storyposts_Settings::get( 'collections_per_load', 10 ) );

		$valid_results = [];

		// Query ALL active collections
		$all_collections = get_posts( [
			'post_type'      => 'stpo_collection',
			'post_status'    => 'publish',
			'posts_per_page' => -1, // Fetch all to filter empty ones and sort in PHP
			'meta_query'     => [
				'relation' => 'OR',
				[
					'key'     => '_stpo_collection_status',
					'value'   => 'active',
					'compare' => '=',
				],
				[
					'key'     => '_stpo_collection_status',
					'compare' => 'NOT EXISTS',
				],
			],
		] );

		// Sort collections in PHP to handle "1 is first, 0/unset is last"
		usort( $all_collections, function( $a, $b ) {
			$order_a = get_post_meta( $a->ID, '_stpo_collection_order', true );
			$order_b = get_post_meta( $b->ID, '_stpo_collection_order', true );

			// Treat 0 or empty/false as a very large number so they appear at the end
			$val_a = ( empty( $order_a ) || ! is_numeric( $order_a ) || (int) $order_a === 0 ) ? 999999 : (int) $order_a;
			$val_b = ( empty( $order_b ) || ! is_numeric( $order_b ) || (int) $order_b === 0 ) ? 999999 : (int) $order_b;

			if ( $val_a === $val_b ) {
				// If orders are same, sort by ID to keep consistent
				return $a->ID < $b->ID ? -1 : 1;
			}

			return $val_a < $val_b ? -1 : 1;
		} );

		foreach ( $all_collections as $collection ) {
			$stories = $this->get_stories_for_collection( $collection->ID );

			// Skip collections with no stories
			if ( empty( $stories ) ) {
				continue;
			}

			// Get collection cover (featured image or first story poster)
			$cover = $this->get_collection_cover( $collection->ID, $stories );

			$valid_results[] = [
				'id'            => $collection->ID,
				'collection_id' => $collection->ID,
				'name'          => html_entity_decode( get_the_title( $collection ), ENT_QUOTES, 'UTF-8' ),
				'avatar'        => $cover, // Using cover as avatar for footer consistency
				'cover'         => $cover,
				'type'          => 'collection',
				'stories'       => $stories,
			];
		}

		// Apply pagination after filtering
		$results = array_slice( $valid_results, $offset, $limit );

		wp_send_json_success( $results );
	}

	/**
	 * Get all stories for a given collection.
	 *
	 * @param int $collection_id Collection post ID.
	 * @return array
	 */
	private function get_stories_for_collection( $collection_id ) {
		$story_ids = get_post_meta( $collection_id, '_stpo_story_ids', true );

		if ( empty( $story_ids ) || ! is_array( $story_ids ) ) {
			return [];
		}

		// Filter out empty values
		$story_ids = array_filter( $story_ids );

		if ( empty( $story_ids ) ) {
			return [];
		}

		$stories = [];

		$max_title = (int) Storyposts_Settings::get( 'collection_max_title_length', 30 );
		$max_desc  = (int) Storyposts_Settings::get( 'collection_max_desc_length', 120 );

		foreach ( $story_ids as $story_id ) {
			$story_id = absint( $story_id );
			$post = get_post( $story_id );

			// Skip if story doesn't exist or isn't published
			if ( ! $post || $post->post_status !== 'publish' ) {
				continue;
			}

			// Gather story details (using same format as user stories)
			$title     = html_entity_decode( get_the_title( $post ), ENT_QUOTES, 'UTF-8' );
			$type      = get_post_meta( $story_id, '_stpo_type', true );
			$caption   = get_post_meta( $story_id, '_stpo_caption', true );
			$link      = get_post_meta( $story_id, '_stpo_link', true );
			$timestamp = get_the_date( 'U', $post );
			$color     = '';
			$src       = '';
			$poster    = '';

			// Handle media types
			if ( $type === 'image' ) {
				$image_id = get_post_meta( $story_id, '_stpo_image_id', true );
				if ( is_numeric( $image_id ) ) {
					$src    = wp_get_attachment_url( $image_id );
					$poster = wp_get_attachment_image_url( $image_id, 'medium' );
				} else {
					$src    = $image_id;
					$poster = $image_id; // Fallback to full image for poster
				}

			} elseif ( $type === 'video' ) {
				$video_id = get_post_meta( $story_id, '_stpo_video_id', true );
				$src      = is_numeric( $video_id ) ? wp_get_attachment_url( $video_id ) : $video_id;

				$poster_id = get_post_meta( $story_id, '_stpo_poster_id', true );
				if ( is_numeric( $poster_id ) ) {
					$poster = wp_get_attachment_image_url( $poster_id, 'medium' );
				} else {
					$poster = $poster_id; // Might be a URL or empty
				}

			} elseif ( $type === 'text' ) {
				$color     = get_post_meta( $story_id, '_stpo_color', true );
				$poster_id = get_post_meta( $story_id, '_stpo_poster_id', true );
				if ( is_numeric( $poster_id ) ) {
					$poster = wp_get_attachment_image_url( $poster_id, 'medium' );
				} else {
					$poster = $poster_id; // Might be a URL or empty
				}
			}

			// Truncate title and caption
			if ( $title && mb_strlen( $title ) > $max_title ) {
				$title = mb_strimwidth( $title, 0, $max_title, '...' );
			}
			if ( $caption && mb_strlen( $caption ) > $max_desc ) {
				$caption = mb_strimwidth( $caption, 0, $max_desc, '...' );
			}

			// Build story response (no privacy/cans for collection stories)
			$stories[] = [
				'id'        => $story_id,
				'title'     => $title,
				'type'      => $type ?: 'text',
				'caption'   => $caption,
				'link'      => $link,
				'timestamp' => human_time_diff( $timestamp, current_time( 'timestamp' ) ) . ' ago',
				'src'       => $src,
				'color'     => $color,
				'poster'    => $poster,
				'seen'      => false, // No seen tracking for collections
				'cans'      => [],    // No edit/delete for public collection stories
			];
		}

		return $stories;
	}

	/**
	 * Get collection cover image.
	 * Uses featured image if set, otherwise falls back to first story poster.
	 *
	 * @param int   $collection_id Collection post ID.
	 * @param array $stories       Array of story data.
	 * @return string Cover image URL.
	 */
	private function get_collection_cover( $collection_id, $stories ) {
		// Try featured image first
		$thumbnail_id = get_post_thumbnail_id( $collection_id );
		if ( $thumbnail_id ) {
			$cover = wp_get_attachment_image_url( $thumbnail_id, 'medium' );
			if ( $cover ) {
				return $cover;
			}
		}

		// Fallback to first story poster
		if ( ! empty( $stories ) && ! empty( $stories[0]['poster'] ) ) {
			return $stories[0]['poster'];
		}

		// Default placeholder
		return '';
	}

}
