<?php

namespace MovieEngine\Frontend;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

use MovieEngine\Utils\TemplateLoader;


/**
 * Class TemplateHooks
 */
class TemplateHooks {

    public static function init() {
        add_action('movie_engine_single_movie_hero', [self::class, 'render_hero_section'], 10);
        add_action('movie_engine_single_movie_content', [self::class, 'render_ad_before_content'], 5);
        $movie_engine_design_options = get_option('movie_engine_design_settings', []);
        $sections_order = isset($movie_engine_design_options['movie_sections_order']) ? $movie_engine_design_options['movie_sections_order'] : 'trending,related,cast,new_releases,upcoming';
        $sections = array_map('trim', explode(',', $sections_order));

        $priority = 10;
        foreach ($sections as $section) {
            switch ($section) {
                case 'trending':
                    add_action('movie_engine_single_movie_content', [self::class, 'render_trending_section'], $priority);
                    break;
                case 'related':
                    add_action('movie_engine_single_movie_content', [self::class, 'render_related_section'], $priority);
                    break;
                case 'cast':
                    add_action('movie_engine_single_movie_content', [self::class, 'render_cast_section'], $priority);
                    break;
                case 'new_releases':
                    add_action('movie_engine_single_movie_content', [self::class, 'render_new_releases_section'], $priority);
                    break;
                case 'upcoming':
                    add_action('movie_engine_single_movie_content', [self::class, 'render_upcoming_section'], $priority);
                    break;
            }
            $priority += 10;
        }

        add_action('movie_engine_single_movie_content', [self::class, 'render_ad_after_content'], 90);
        add_action('movie_engine_single_movie_content', [self::class, 'render_reviews_section'], 100);
        add_action('movie_engine_single_series_hero', [self::class, 'render_series_hero_section'], 10);
        $series_sections_order = isset($movie_engine_design_options['series_sections_order']) ? $movie_engine_design_options['series_sections_order'] : 'ad_before,episodes,cast,trending,related,new_releases,upcoming';
        $series_sections = array_map('trim', explode(',', $series_sections_order));
        if (!in_array('ad_before', $series_sections)) {
            $ep_index = array_search('episodes', $series_sections);
            if ($ep_index === false) $ep_index = array_search('seasons', $series_sections);

            if ($ep_index !== false) {
                array_splice($series_sections, $ep_index + 1, 0, 'ad_before');
            } else {
                array_unshift($series_sections, 'ad_before');
            }
        }

        $s_priority = 10;
        foreach ($series_sections as $section) {
            switch ($section) {
                case 'ad_before':
                    add_action('movie_engine_single_series_content', [self::class, 'render_ad_before_content'], $s_priority);
                    break;
                case 'episodes':
                case 'seasons':
                    add_action('movie_engine_single_series_content', [self::class, 'render_episodes_section'], $s_priority);
                    break;
                case 'cast':
                    add_action('movie_engine_single_series_content', [self::class, 'render_series_cast_section'], $s_priority);
                    break;
                case 'trending':
                    add_action('movie_engine_single_series_content', [self::class, 'render_series_trending_section'], $s_priority);
                    break;
                case 'new_releases':
                    add_action('movie_engine_single_series_content', [self::class, 'render_series_new_releases_section'], $s_priority);
                    break;
                case 'upcoming':
                    add_action('movie_engine_single_series_content', [self::class, 'render_series_upcoming_section'], $s_priority);
                    break;
                case 'related':
                    add_action('movie_engine_single_series_content', [self::class, 'render_series_related_section'], $s_priority);
                    break;
            }
            $s_priority += 10;
        }

        add_action('movie_engine_single_series_content', [self::class, 'render_ad_after_content'], 90);
        add_action('movie_engine_single_series_content', [self::class, 'render_reviews_section'], 100);

        $episode_sections_order = isset($movie_engine_design_options['episode_sections_order']) ? $movie_engine_design_options['episode_sections_order'] : 'episodes,trending,related';
        $episode_sections = array_map('trim', explode(',', $episode_sections_order));

        $e_priority = 10;
        foreach ($episode_sections as $section) {
            switch ($section) {
                case 'episodes':
                case 'seasons':
                    add_action('movie_engine_single_episode_sections', [self::class, 'render_episodes_section'], $e_priority);
                    break;
                case 'trending':
                    add_action('movie_engine_single_episode_sections', [self::class, 'render_episode_trending_section'], $e_priority);
                    break;
                case 'related':
                    add_action('movie_engine_single_episode_sections', [self::class, 'render_episode_related_section'], $e_priority);
                    break;
            }
            $e_priority += 10;
        }

        add_action('movie_engine_single_episode_sections', [self::class, 'render_reviews_section'], 100);
        add_action('movie_engine_archive_before_grid', [self::class, 'render_filter_bar'], 10);
        add_action('movie_engine_archive_content', [self::class, 'render_archive_grid'], 10);
        add_action('movie_engine_archive_after_grid', [self::class, 'render_pagination'], 10);
    }

    /*
     * --------------------------------------------------------------------------
     * Single Movie Renderers
     * --------------------------------------------------------------------------
     */

    public static function render_hero_section() {
        TemplateLoader::get_template_part('single-movie/hero-fullwidth');
    }

    public static function render_ad_before_content() {
        do_action('movie_engine_ad_before_content');
    }

    public static function render_ad_after_content() {
        do_action('movie_engine_ad_after_content');
    }

    public static function render_ad_player_top() {
        do_action('movie_engine_ad_player_top');
    }

    public static function render_ad_player_bottom() {
        do_action('movie_engine_ad_player_bottom');
    }

    public static function render_trending_section() {
        TemplateLoader::get_template_part('single-movie/section-trending');
    }

    public static function render_related_section() {
        TemplateLoader::get_template_part('single-movie/section-related');
    }

    public static function render_cast_section() {
        TemplateLoader::get_template_part('single-movie/section-cast');
    }

    public static function render_new_releases_section() {
        TemplateLoader::get_template_part('single-movie/section-new-releases');
    }

    public static function render_upcoming_section() {
        TemplateLoader::get_template_part('single-movie/section-upcoming');
    }

    public static function render_reviews_section() {
        global $post;
        if (!$post) return;

        if (comments_open($post->ID) || get_comments_number($post->ID)) {
            add_filter('comments_template', [self::class, 'filter_comments_template']);
            comments_template();
            remove_filter('comments_template', [self::class, 'filter_comments_template']);
        }
    }

    /**
     * Custom callback for rendering comments/reviews
     */
    public static function comment_callback($comment, $args, $depth) {
        $GLOBALS['comment'] = $comment;
        TemplateLoader::get_template_part('global/review-item', '', [
            'comment' => $comment,
            'args'    => $args,
            'depth'   => $depth
        ]);
    }


    public static function filter_comments_template($template) {
        $plugin_template = TemplateLoader::get_template_path('global/reviews.php');
        if (file_exists($plugin_template)) {
            return $plugin_template;
        }
        return $template;
    }

    /*
     * ------------------------
     * Single Series Renderers
     * ------------------------
     */

    public static function render_series_hero_section() {
        TemplateLoader::get_template_part('single-series/hero');
    }

    public static function render_episodes_section() {
        if (is_singular('movie_engine_episode')) {
            $options = get_option('movie_engine_design_settings', []);
            $layout = $options['episode_single_layout'] ?? 'sidebar';
            if ($layout === 'sidebar') {
                return;
            }
        }
        TemplateLoader::get_template_part('single-series/episodes');
    }

    public static function render_series_cast_section() {
        TemplateLoader::get_template_part('single-series/section-cast');
    }

    public static function render_series_trending_section() {
        TemplateLoader::get_template_part('single-series/section-trending');
    }

    public static function render_series_new_releases_section() {
        TemplateLoader::get_template_part('single-series/section-new-releases');
    }

    public static function render_series_upcoming_section() {
        TemplateLoader::get_template_part('single-series/section-upcoming');
    }

    public static function render_series_related_section() {
        TemplateLoader::get_template_part('single-series/section-related');
    }

    /*
     * ---------------------------------
     * Single Episode Renderers
     * ---------------------------------
     */

    public static function render_episode_trending_section() {
        $design = get_option('movie_engine_design_settings', []);
        $layout = $design['episode_single_layout'] ?? 'sidebar';

        if ($layout === 'sidebar') {
            return;
        }

        TemplateLoader::get_template_part('single-episode/section-trending');
    }

    public static function render_episode_related_section() {
        TemplateLoader::get_template_part('single-episode/section-related');
    }

    /*
     * ------------------------
     * Archive Renderers
     * ------------------------
     */

    public static function render_filter_bar() {
        TemplateLoader::get_template_part('archive/filter-bar');
    }

    public static function render_archive_grid() {
        if (have_posts()) {
            $design = get_option('movie_engine_design_settings', []);
            $cols = $design['archive_columns_desktop'] ?? 4;
            $cols_laptop = $design['archive_columns_laptop'] ?? 4;
            $cols_tablet = $design['archive_columns_tablet'] ?? 3;
            $cols_mobile = $design['archive_columns_mobile'] ?? 2;

            $style = "style='--me-grid-columns-desktop: " . esc_attr($cols) . "; --me-grid-columns-laptop: " . esc_attr($cols_laptop) . "; --me-grid-columns-tablet: " . esc_attr($cols_tablet) . "; --me-grid-columns-mobile: " . esc_attr($cols_mobile) . ";'";

            echo '<div class="movie-engine-movie-grid" ' . $style . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            while (have_posts()) {
                the_post();
                TemplateLoader::get_template_part('loop/content-movie');
            }
            echo '</div>';
        } else {
            echo '<div class="movie-engine-no-results"><p>' . esc_html__('No movies found.', 'cine-movie-engine') . '</p></div>';
        }
    }

    public static function render_pagination() {
        if (!have_posts()) return;

        $design = get_option('movie_engine_design_settings', []);
        $type = $design['pagination_type'] ?? 'numbers';

        if (!apply_filters('movie_engine_is_pro', false)) {
            $type = 'numbers';
        }

        global $wp_query;
        $max_pages = $wp_query->max_num_pages;
        $paged = max(1, get_query_var('paged'));

        echo '<nav class="movie-engine-pagination" data-type="' . esc_attr($type) . '" data-max-pages="' . esc_attr($max_pages) . '" aria-label="' . esc_attr__('Pagination', 'cine-movie-engine') . '">';

        if ($type === 'numbers' && $max_pages > 1) {
            $big = 999999999;
            $pagination_links = paginate_links([
                'base'      => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                'format'    => '?paged=%#%',
                'current'   => $paged,
                'total'     => $max_pages,
                'prev_text' => '<span class="fa-solid fa-angle-left" aria-hidden="true"></span><span class="me-sr-only">' . esc_html__('Previous', 'cine-movie-engine') . '</span>',
                'next_text' => '<span class="fa-solid fa-angle-right" aria-hidden="true"></span><span class="me-sr-only">' . esc_html__('Next', 'cine-movie-engine') . '</span>',
            ]);
            if ($pagination_links) {
                $pagination_links = str_replace('class="prev page-numbers"', 'class="prev page-numbers" aria-label="' . esc_attr__('Previous Page', 'cine-movie-engine') . '"', $pagination_links);
                $pagination_links = str_replace('class="next page-numbers"', 'class="next page-numbers" aria-label="' . esc_attr__('Next Page', 'cine-movie-engine') . '"', $pagination_links);
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
                echo \MovieEngine\Utils\Helpers::kses_post((string) $pagination_links);
            }
        } elseif (($type === 'load_more' || $type === 'infinite') && $max_pages > 1) {
            // Delegate advanced pagination markup to Pro plugin
            do_action('movie_engine_render_pro_pagination', $type, $max_pages, $paged);
        }

        echo '</nav>';
    }
}
