<?php

/**
 * The template for displaying episode sidebar
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/single-episode/sidebar.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; // Exit if accessed directly
}

$movie_engine_series_id = get_post_meta(get_the_ID(), '_movie_engine_series_id', true);
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$movie_engine_current_season = isset($_GET['season']) ? absint(wp_unslash($_GET['season'])) : get_post_meta(get_the_ID(), '_movie_engine_season_number', true);
$movie_engine_current_episode_id = get_the_ID();

$movie_engine_episodes_query = new WP_Query([
    'post_type'      => 'movie_engine_episode',
    'posts_per_page' => -1,
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
    'meta_key'       => '_movie_engine_episode_number',
    'orderby'        => 'meta_value_num',
    'order'          => 'ASC',
    // phpcs:ignore WordPress.DB.SlowDBQuery
    '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_seasons_query_obj = 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
    'meta_query'     => [
        [
            'key'   => '_movie_engine_series_id',
            'value' => $movie_engine_series_id,
        ],
    ],
]);

$movie_engine_available_seasons = [];
if ($movie_engine_seasons_query_obj->have_posts()) {
    while ($movie_engine_seasons_query_obj->have_posts()) {
        $movie_engine_seasons_query_obj->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 = [$movie_engine_current_season];
    }
}
?>

<div class="movie-engine-episode-playlist"
    data-series-id="<?php echo esc_attr($movie_engine_series_id); ?>"
    data-current-season="<?php echo esc_attr($movie_engine_current_season); ?>"
    data-current-episode-id="<?php echo esc_attr($movie_engine_current_episode_id); ?>">
    <div class="me-playlist-header">
        <div class="me-header-left">
            <h3>
                <?php
                printf(
                    /* translators: %d: season number */
                    esc_html__('Season %d', 'cine-movie-engine'),
                    absint($movie_engine_current_season)
                );
                ?>
            </h3>
            <span class="me-episode-count">
                <?php
                printf(
                    /* translators: %d: number of episodes */
                    esc_html__('%d Episodes', 'cine-movie-engine'),
                    absint($movie_engine_episodes_query->post_count)
                );
                ?>
            </span>
        </div>

        <?php if (count($movie_engine_available_seasons) > 1) : ?>
            <div class="me-header-right">
                <select class="me-season-select me-ajax-season-select">
                    <?php foreach ($movie_engine_available_seasons as $movie_engine_season_num_item) : ?>
                        <option value="<?php echo intval($movie_engine_season_num_item); ?>" <?php selected($movie_engine_current_season, $movie_engine_season_num_item); ?>>
                            <?php
                            printf(
                                /* translators: %d: season number */
                                esc_html__('Season %d', 'cine-movie-engine'),
                                absint($movie_engine_season_num_item)
                            );
                            ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>
    </div>
    <div class="me-playlist-items">
        <?php if ($movie_engine_episodes_query->have_posts()) : ?>
            <?php while ($movie_engine_episodes_query->have_posts()) : $movie_engine_episodes_query->the_post();
                $movie_engine_loop_ep_id = get_the_ID();
                $movie_engine_loop_ep_num = get_post_meta($movie_engine_loop_ep_id, '_movie_engine_episode_number', true);
                $movie_engine_loop_ep_runtime = get_post_meta($movie_engine_loop_ep_id, '_movie_engine_runtime', true);
                $movie_engine_loop_thumb = get_the_post_thumbnail_url($movie_engine_loop_ep_id, 'medium');

                if (!$movie_engine_loop_thumb) {
                    $movie_engine_loop_thumb = get_post_meta($movie_engine_series_id, '_movie_engine_backdrop_url', true);
                    if (!$movie_engine_loop_thumb) {
                        $movie_engine_loop_thumb = get_the_post_thumbnail_url($movie_engine_series_id, 'medium');
                    }
                }
                if (!$movie_engine_loop_thumb) {
                    $movie_engine_loop_thumb = MOVIE_ENGINE_URL . 'assets/images/episode-placeholder.svg';
                }

                $movie_engine_loop_is_active = ($movie_engine_loop_ep_id === $movie_engine_current_episode_id);
            ?>
                <a href="<?php the_permalink(); ?>" class="me-playlist-item <?php echo esc_attr($movie_engine_loop_is_active ? 'active' : ''); ?>">
                    <div class="me-item-thumb">
                        <img src="<?php echo esc_url($movie_engine_loop_thumb); ?>" alt="<?php the_title_attribute(); ?>">
                        <?php if ($movie_engine_loop_is_active) : ?>
                            <div class="me-playing-overlay">
                                <span class="fa-solid fa-play"></span>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="me-item-info">
                        <span class="me-ep-num">
                            <?php
                            printf(
                                /* translators: %s: episode number */
                                esc_html__('Episode %s', 'cine-movie-engine'),
                                esc_html($movie_engine_loop_ep_num)
                            );
                            ?>
                        </span>
                        <h4 class="me-ep-title"><?php echo esc_html(get_the_title()); ?></h4>
                        <?php if ($movie_engine_loop_ep_runtime) : ?>
                            <span class="me-ep-runtime"><?php echo esc_html($movie_engine_loop_ep_runtime); ?>m</span>
                        <?php endif; ?>
                    </div>
                </a>
            <?php endwhile;
            wp_reset_postdata(); ?>
        <?php endif; ?>
    </div>
</div>