<?php

/**
 * The template for displaying series episodes list
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/single-series/episodes.php.
 *
 * HOWEVER, on occasion MovieEngine will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @note Please do not delete our CSS classes when you customize, as it may break functionality.
 * @package Movie_Engine
 * @subpackage Movie_Engine/templates
 * @version 1.0.0
 * @since 1.0.0
 */

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

$movie_engine_options = get_option('movie_engine_design_settings', []);

$movie_engine_post_id = get_the_ID();
$movie_engine_post_type = get_post_type($movie_engine_post_id);
$movie_engine_is_episode_page = ($movie_engine_post_type === 'movie_engine_episode');
$movie_engine_prefix = $movie_engine_is_episode_page ? 'episode_' : 'series_';

if (isset($movie_engine_options[$movie_engine_prefix . 'show_seasons']) && !$movie_engine_options[$movie_engine_prefix . 'show_seasons']) {
    return;
}

$movie_engine_series_id = ($movie_engine_post_type === 'movie_engine_episode') ? get_post_meta($movie_engine_post_id, '_movie_engine_series_id', true) : $movie_engine_post_id;

$movie_engine_section_title  = $movie_engine_options[$movie_engine_prefix . 'seasons_title'] ?? esc_html__('Episodes', 'cine-movie-engine');
$movie_engine_layout         = $movie_engine_options[$movie_engine_prefix . 'seasons_layout'] ?? 'list';
$movie_engine_sort_order     = $movie_engine_options[$movie_engine_prefix . 'episodes_order'] ?? 'asc';
$movie_engine_items_per_page = $movie_engine_options[$movie_engine_prefix . 'episodes_count'] ?? 20;

$movie_engine_seasons_query = new WP_Query([
    'post_type'      => 'movie_engine_season',
    'posts_per_page' => -1,
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
    'meta_key'       => '_movie_engine_season_number',
    'orderby'        => 'meta_value_num',
    'order'          => 'ASC',
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
    'meta_query'     => [
        [
            'key'   => '_movie_engine_series_id',
            'value' => $movie_engine_series_id,
        ],
    ],
]);

$movie_engine_available_seasons = [];
if ($movie_engine_seasons_query->have_posts()) {
    while ($movie_engine_seasons_query->have_posts()) {
        $movie_engine_seasons_query->the_post();
        $movie_engine_s_num = get_post_meta(get_the_ID(), '_movie_engine_season_number', true);
        if ($movie_engine_s_num) $movie_engine_available_seasons[] = intval($movie_engine_s_num);
    }
    wp_reset_postdata();
}

if (empty($movie_engine_available_seasons)) {
    $movie_engine_manual_count = intval(get_post_meta($movie_engine_series_id, '_movie_engine_seasons_count', true));
    if ($movie_engine_manual_count > 1) {
        $movie_engine_available_seasons = range(1, $movie_engine_manual_count);
    } else {
        $movie_engine_available_seasons = [1];
    }
}

$movie_engine_total_seasons_count = count($movie_engine_available_seasons);

// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$movie_engine_current_season = isset($_GET['season']) ? intval($_GET['season']) : 1;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ($movie_engine_post_type === 'movie_engine_episode' && !isset($_GET['season'])) {
    $movie_engine_current_season = get_post_meta($movie_engine_post_id, '_movie_engine_season_number', true) ?: 1;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$movie_engine_current_page = isset($_GET['ep_page']) ? intval($_GET['ep_page']) : 1;

$movie_engine_args = [
    'post_type'      => 'movie_engine_episode',
    'posts_per_page' => $movie_engine_items_per_page,
    'paged'          => $movie_engine_current_page,
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
    'meta_key'       => '_movie_engine_episode_number',
    'orderby'        => 'meta_value_num',
    'order'          => strtoupper(sanitize_text_field($movie_engine_sort_order)),
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
    'meta_query'     => [
        'relation' => 'AND',
        [
            'key'   => '_movie_engine_series_id',
            'value' => $movie_engine_series_id,
        ],
        [
            'key'   => '_movie_engine_season_number',
            'value' => $movie_engine_current_season,
        ],
    ],
];

$movie_engine_episodes = new WP_Query($movie_engine_args);

$movie_engine_grid_style = '';
if ($movie_engine_layout === 'grid') {
    $movie_engine_cols_desktop = $movie_engine_options[$movie_engine_prefix . 'episodes_columns'] ?? 4;
    $movie_engine_cols_laptop  = $movie_engine_options[$movie_engine_prefix . 'episodes_columns_laptop'] ?? 4;
    $movie_engine_cols_tablet  = $movie_engine_options[$movie_engine_prefix . 'episodes_columns_tablet'] ?? 3;
    $movie_engine_cols_mobile  = $movie_engine_options[$movie_engine_prefix . 'episodes_columns_mobile'] ?? 1;

    $movie_engine_grid_style = "style='--me-grid-columns-desktop: " . esc_attr($movie_engine_cols_desktop) . "; --me-grid-columns-laptop: " . esc_attr($movie_engine_cols_laptop) . "; --me-grid-columns-tablet: " . esc_attr($movie_engine_cols_tablet) . "; --me-grid-columns-mobile: " . esc_attr($movie_engine_cols_mobile) . ";'";
}
?>

<div class="movie-engine-section movie-engine-episodes-section me-pt-0"
    data-series-id="<?php echo esc_attr($movie_engine_series_id); ?>"
    data-season="<?php echo esc_attr($movie_engine_current_season); ?>"
    data-per-page="<?php echo esc_attr($movie_engine_items_per_page); ?>"
    data-layout="<?php echo esc_attr($movie_engine_layout); ?>"
    data-current-episode-id="<?php echo esc_attr($movie_engine_post_id); ?>">
    <div class="movie-engine-section-header">
        <h2 class="movie-engine-section-title"><?php echo esc_html($movie_engine_section_title); ?></h2>

        <?php if ($movie_engine_total_seasons_count > 1 || $movie_engine_episodes->max_num_pages > 1) : ?>
            <div class="movie-engine-season-selector-group">
                <?php if ($movie_engine_total_seasons_count > 1) : ?>
                    <div class="movie-engine-season-selector-wrapper">
                        <select class="movie-engine-season-dropdown" onchange="window.location.href=this.value">
                            <?php foreach ($movie_engine_available_seasons as $movie_engine_season_num) : ?>
                                <?php
                                $movie_engine_url = add_query_arg('season', $movie_engine_season_num);
                                ?>
                                <option value="<?php echo esc_url($movie_engine_url); ?>" <?php selected($movie_engine_current_season, $movie_engine_season_num); ?>>
                                    <?php printf(
                                        /* translators: %d: Season Number */
                                        esc_html__('Season %d', 'cine-movie-engine'),
                                        absint($movie_engine_season_num)
                                    ); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endif; ?>

                <?php if (!$movie_engine_is_episode_page && $movie_engine_episodes->max_num_pages > 1) : ?>
                    <?php
                    $movie_engine_first_ep_url = '#';
                    if (!empty($movie_engine_episodes->posts[0])) {
                        $movie_engine_first_ep_url = get_permalink($movie_engine_episodes->posts[0]->ID);
                    }
                    ?>
                    <a href="<?php echo esc_url($movie_engine_first_ep_url); ?>" class="movie-engine-view-all-link">
                        <?php esc_html_e('View All', 'cine-movie-engine'); ?>
                        <span class="fa-solid fa-angle-right" aria-hidden="true"></span>
                    </a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="movie-engine-episodes-container <?php echo esc_attr($movie_engine_layout === "grid" ? "movie-engine-grid-layout" : "movie-engine-list-layout"); ?>" <?php echo $movie_engine_grid_style; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> >
        <?php if ($movie_engine_episodes->have_posts()) : ?>
            <?php while ($movie_engine_episodes->have_posts()) : $movie_engine_episodes->the_post();
                $movie_engine_episode_id = get_the_ID();
                $movie_engine_episode_num = get_post_meta($movie_engine_episode_id, '_movie_engine_episode_number', true);
                $movie_engine_duration = get_post_meta($movie_engine_episode_id, '_movie_engine_runtime', true);
                $movie_engine_thumbnail = get_the_post_thumbnail_url($movie_engine_episode_id, 'large');

                if (!$movie_engine_thumbnail) {
                    $movie_engine_thumbnail = get_post_meta($movie_engine_series_id, '_movie_engine_backdrop_url', true);
                    if (!$movie_engine_thumbnail) {
                        $movie_engine_thumbnail = get_the_post_thumbnail_url($movie_engine_series_id, 'large');
                    }
                }

                if (!$movie_engine_thumbnail) {
                    $movie_engine_thumbnail = MOVIE_ENGINE_URL . 'assets/images/episode-placeholder.svg';
                }

                $movie_engine_is_active = ($movie_engine_is_episode_page && $movie_engine_episode_id == $movie_engine_post_id);
                $movie_engine_active_class = $movie_engine_is_active ? 'is-active' : '';
            ?>

                <?php if ($movie_engine_layout === 'list') : ?>
                    <a href="<?php the_permalink(); ?>" class="movie-engine-episode-list-item <?php echo esc_attr($movie_engine_active_class); ?>" aria-label="<?php the_title_attribute(); ?>">
                        <div class="me-episode-index"><?php echo esc_html($movie_engine_episode_num); ?></div>
                        <div class="me-episode-thumb">
                            <img src="<?php echo esc_url($movie_engine_thumbnail); ?>" alt="<?php the_title_attribute(); ?>">
                            <span class="me-play-icon"><span class="fa-solid fa-play" aria-hidden="true"></span></span>
                        </div>
                        <div class="me-episode-info">
                            <h3 class="me-episode-title">
                                <?php echo esc_html(get_the_title()); ?>
                                <?php if ($movie_engine_duration) : ?><span class="me-duration"><?php echo esc_html($movie_engine_duration); ?></span><?php endif; ?>
                            </h3>
                            <div class="me-episode-excerpt"><?php echo \MovieEngine\Utils\Helpers::kses_post(wp_strip_all_tags(get_the_excerpt())); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML ?></div>
                        </div>
                        <div class="me-episode-meta">
                            <span class="me-date"><?php echo esc_html(get_the_date()); ?></span>
                        </div>
                    </a>
                <?php else : ?>
                    <div class="movie-engine-episode-card <?php echo esc_attr($movie_engine_active_class); ?>">
                        <a href="<?php the_permalink(); ?>" class="me-episode-thumb-wrapper" aria-label="<?php the_title_attribute(); ?>">
                            <img src="<?php echo esc_url($movie_engine_thumbnail); ?>" alt="<?php the_title_attribute(); ?>">
                            <div class="me-episode-overlay">
                                <span class="fa-solid fa-play" aria-hidden="true"></span>
                            </div>
                            <?php if ($movie_engine_episode_num) : ?>
                                <span class="me-episode-badge">
                                    <?php printf(
                                        /* translators: %s: episode number */
                                        esc_html__('Ep %s', 'cine-movie-engine'),
                                        esc_html($movie_engine_episode_num)
                                    ); ?>
                                </span>
                            <?php endif; ?>
                        </a>
                        <div class="me-episode-content">
                            <h3 class="me-episode-title"><a href="<?php the_permalink(); ?>"><?php echo esc_html(get_the_title()); ?></a></h3>
                            <div class="me-episode-meta">
                                <?php if ($movie_engine_duration) : ?>
                                    <span class="me-meta-item">
                                        <span class="fa-solid fa-clock" aria-hidden="true"></span> <?php echo esc_html($movie_engine_duration); ?>m
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

            <?php endwhile; ?>
            <?php wp_reset_postdata(); ?>
        <?php else : ?>
            <div class="movie-engine-no-episodes">
                <p><?php esc_html_e('No episodes found for this season.', 'cine-movie-engine'); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <?php if ($movie_engine_episodes->max_num_pages > 1) : ?>
        <nav class="movie-engine-pagination" aria-label="<?php esc_attr_e('Episodes pagination', 'cine-movie-engine'); ?>">
            <?php
            $pagination_links = paginate_links([
                'base' => add_query_arg('ep_page', '%#%'),
                'format' => '',
                'current' => $movie_engine_current_page,
                'total' => $movie_engine_episodes->max_num_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>',
                'type' => 'list'
            ]);
            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);
            }
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
            ?>
        </nav>
    <?php endif; ?>
</div>