<?php
/********************************************************************
 * Copyright (C) 2024 Darko Gjorgjijoski (https://darkog.com/)
 * Copyright (C) 2024 IDEOLOGIX MEDIA Dooel (https://ideologix.com/)
 *
 * This file is property of IDEOLOGIX MEDIA Dooel (https://ideologix.com)
 * This file is part of Vimeify Plugin - https://wordpress.org/plugins/vimeify/
 *
 * Vimeify - Formerly "WP Vimeo Videos" is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 2 of the License,
 * or (at your option) any later version.
 *
 * Vimeify - Formerly "WP Vimeo Videos" is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this plugin. If not, see <https://www.gnu.org/licenses/>.
 *
 * Code developed by Darko Gjorgjijoski <dg@darkog.com>.
 **********************************************************************/

namespace Vimeify\Core\Frontend\Views;

use Vimeify\Core\Abstracts\BaseView;
use Vimeify\Core\Backend\Galleries;
use Vimeify\Core\Components\Database;

class GalleryView extends BaseView {

	protected $styles = [ 'vimeify-gallery' ];
	protected $scripts = [ 'vimeify-gallery' ];

	/**
	 * Set the defaults
	 *
	 * @param array $args
	 */
	function set_defaults() {
		$this->defaults = [
			'id'     => 0,
			'page'   => 1,
			'offset' => 0,
		];
	}

	/**
	 * Handles the output
	 * @return string
	 */
	protected function get_output() {
		// Enqueue assets when rendering
		$this->enqueue();

		$gallery_id = isset( $this->args['id'] ) ? intval( $this->args['id'] ) : 0;
		$page = isset( $this->args['page'] ) ? intval( $this->args['page'] ) : 1;
		$offset = isset( $this->args['offset'] ) ? intval( $this->args['offset'] ) : 0;

		if ( empty( $gallery_id ) ) {
			return '<p>' . esc_html__( 'Invalid gallery ID.', 'vimeify' ) . '</p>';
		}

		// Get gallery term
		$gallery = get_term( $gallery_id, Database::TAXONOMY_GALLERY );
		if ( ! $gallery || is_wp_error( $gallery ) ) {
			return '<p>' . esc_html__( 'Gallery not found.', 'vimeify' ) . '</p>';
		}

		// Get gallery type and settings
		$gallery_type = Galleries::get_gallery_type( $gallery_id );
		$gallery_settings = Galleries::get_gallery_settings( $gallery_id );

		// Get display style
		$display_style = isset( $gallery_settings['display_style'] ) ? $gallery_settings['display_style'] : 'slider';

		// Get pagination settings
		$per_page = $this->get_per_page_limit( $gallery_settings );

		// Get ordering settings
		$orderby = isset( $gallery_settings['orderby'] ) ? $gallery_settings['orderby'] : 'date';
		$order = isset( $gallery_settings['order'] ) ? $gallery_settings['order'] : 'desc';

		// Build query args
		$query_args = [
			'post_type'      => Database::POST_TYPE_VIDEO,
			'post_status'    => 'publish',
			'posts_per_page' => $per_page > 0 ? $per_page : -1,
			'paged'          => $page,
			'tax_query'      => [
				[
					'taxonomy' => Database::TAXONOMY_GALLERY,
					'field'    => 'term_id',
					'terms'    => $gallery_id,
				],
			],
		];

		// Apply ordering
		if ( $orderby === 'date' ) {
			$query_args['orderby'] = 'date';
			$query_args['order'] = strtoupper( $order );
		} elseif ( $orderby === 'title' ) {
			$query_args['orderby'] = 'title';
			$query_args['order'] = strtoupper( $order );
		} else {
			// Default to date ordering
			$query_args['orderby'] = 'date';
			$query_args['order'] = 'DESC';
		}

		// Handle offset for custom pagination
		if ( $offset > 0 ) {
			$query_args['offset'] = $offset;
			unset( $query_args['paged'] );
		}

		// Allow filtering of query args
		$query_args = apply_filters( 'vimeify_gallery_query_args', $query_args, $gallery_id, $gallery_type, $this->plugin );

		// Execute query
		$video_query = new \WP_Query( $query_args );
		$total_videos = $video_query->found_posts;

		// Format videos for template
		$videos = $this->format_video_posts( $video_query->posts );

		// Allow filtering of videos
		$videos = apply_filters( 'vimeify_gallery_videos', $videos, $gallery_id, $gallery_type, $this->plugin );

		// Calculate current offset for pagination
		$current_offset = $offset > 0 ? $offset : ( ( $page - 1 ) * $per_page );

		// Prepare data for template
		$data = [
			'gallery_id'      => $gallery_id,
			'gallery'         => $gallery,
			'gallery_type'    => $gallery_type,
			'display_style'   => $display_style,
			'settings'        => $gallery_settings,
			'videos'          => $videos,
			'total_videos'    => $total_videos,
			'per_page'        => $per_page,
			'current_page'    => $page,
			'current_offset'  => $current_offset,
			'has_more'        => ( $per_page > 0 && ( $current_offset + $per_page ) < $total_videos ),
		];

		// Allow filtering of data
		$data = apply_filters( 'vimeify_gallery_data', $data, $gallery_id, $this->plugin );

		// Render based on display style
		$output = $this->render_gallery( $data );

		// Allow filtering of output
		$output = apply_filters( 'vimeify_gallery_output', $output, $data, $this->plugin );
		$output = apply_filters( "vimeify_gallery_output_{$display_style}", $output, $data, $this->plugin );

		return $output;
	}

	/**
	 * Get per page limit (respects free version limit of 10)
	 *
	 * @param array $settings
	 *
	 * @return int
	 */
	protected function get_per_page_limit( $settings ) {
		$per_page = isset( $settings['posts_per_page'] ) ? intval( $settings['posts_per_page'] ) : 10;

		// Apply free version limit (max 10)
		$max_limit = apply_filters( 'vimeify_gallery_max_per_page', 10, $this->plugin );

		if ( $per_page > $max_limit ) {
			$per_page = $max_limit;
		}

		return $per_page;
	}

	/**
	 * Format video posts for template
	 *
	 * @param array $posts Array of WP_Post objects
	 *
	 * @return array
	 */
	protected function format_video_posts( $posts ) {
		if ( empty( $posts ) ) {
			return [];
		}

		$videos = [];
		foreach ( $posts as $post ) {
			if ( $post && $post->post_type === Database::POST_TYPE_VIDEO ) {
				$vimeo_id = $this->plugin->system()->database()->get_vimeo_id( $post->ID );
				$videos[] = [
					'ID'          => $post->ID,
					'title'       => $post->post_title,
					'description' => $post->post_content,
					'date'        => $post->post_date,
					'vimeo_id'    => $vimeo_id,
					'thumbnail'   => $this->plugin->system()->vimeo()->get_thumbnail( $vimeo_id, 'large' ),
					'embed_link'  => get_post_meta( $post->ID, 'vimeify_embed_link', true ),
				];
			}
		}

		return $videos;
	}

	/**
	 * Render gallery output
	 *
	 * @param array $data
	 *
	 * @return string
	 */
	protected function render_gallery( $data ) {
		$display_style = $data['display_style'];

		// Try to load style-specific template
		$template_path = "frontend/partials/gallery-{$display_style}";

		// Check if template exists
		$template_file = $this->plugin->system()->views()->get_path( $template_path );

		if ( file_exists( $template_file ) ) {
			$output = $this->plugin->system()->views()->get_view( $template_path, $data );
		} else {
			// Fallback to default slider template
			$output = $this->plugin->system()->views()->get_view( 'frontend/partials/gallery-slider', $data );
		}

		return $output;
	}
}
