<?php

/**
 * The template for displaying episode player data
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/single-episode/player-data.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_post_id = get_the_ID();
$movie_engine_series_id = get_post_meta($movie_engine_post_id, '_movie_engine_series_id', true);
$movie_engine_season_num = get_post_meta($movie_engine_post_id, '_movie_engine_season_number', true);
$movie_engine_episode_num = get_post_meta($movie_engine_post_id, '_movie_engine_episode_number', true);

$movie_engine_next_ep_query = get_posts([
    'post_type' => 'movie_engine_episode',
    // 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_season_num],
        ['key' => '_movie_engine_episode_number', 'value' => $movie_engine_episode_num + 1]
    ],
    'posts_per_page' => 1
]);
$movie_engine_prev_ep_query = get_posts([
    'post_type' => 'movie_engine_episode',
    // 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_season_num],
        ['key' => '_movie_engine_episode_number', 'value' => $movie_engine_episode_num - 1]
    ],
    'posts_per_page' => 1
]);

$movie_engine_episode_nav_data = [];

if (!empty($movie_engine_next_ep_query)) {
    $movie_engine_next_post_obj = $movie_engine_next_ep_query[0];
    $movie_engine_next_ep_num_val = get_post_meta($movie_engine_next_post_obj->ID, '_movie_engine_episode_number', true);
    $movie_engine_next_thumb = get_the_post_thumbnail_url($movie_engine_next_post_obj->ID, 'medium');
    if (!$movie_engine_next_thumb) {
        $movie_engine_next_thumb = get_post_meta($movie_engine_series_id, '_movie_engine_backdrop_url', true);
        if (!$movie_engine_next_thumb) {
            $movie_engine_next_thumb = get_the_post_thumbnail_url($movie_engine_series_id, 'medium');
        }
    }
    $movie_engine_episode_nav_data['next'] = [
        'id' => $movie_engine_next_post_obj->ID,
        'title' => sprintf(
            /* translators: 1: season number, 2: episode number, 3: episode title */
            esc_html__('S%1$dE%2$d: %3$s', 'cine-movie-engine'),
            absint($movie_engine_season_num),
            absint($movie_engine_next_ep_num_val),
            esc_html($movie_engine_next_post_obj->post_title)
        ),
        'url' => get_permalink($movie_engine_next_post_obj->ID),
        'thumbnail' => $movie_engine_next_thumb
    ];
}

if (!empty($movie_engine_prev_ep_query)) {
    $movie_engine_prev_post_obj = $movie_engine_prev_ep_query[0];
    $movie_engine_prev_ep_num_val = get_post_meta($movie_engine_prev_post_obj->ID, '_movie_engine_episode_number', true);

    $movie_engine_prev_thumb = get_the_post_thumbnail_url($movie_engine_prev_post_obj->ID, 'medium');
    if (!$movie_engine_prev_thumb) {
        $movie_engine_prev_thumb = get_post_meta($movie_engine_series_id, '_movie_engine_backdrop_url', true);
        if (!$movie_engine_prev_thumb) {
            $movie_engine_prev_thumb = get_the_post_thumbnail_url($movie_engine_series_id, 'medium');
        }
    }

    $movie_engine_episode_nav_data['prev'] = [
        'id' => $movie_engine_prev_post_obj->ID,
        'title' => sprintf(
            /* translators: 1: season number, 2: episode number, 3: episode title */
            esc_html__('S%1$dE%2$d: %3$s', 'cine-movie-engine'),
            absint($movie_engine_season_num),
            absint($movie_engine_prev_ep_num_val),
            esc_html($movie_engine_prev_post_obj->post_title)
        ),
        'url' => get_permalink($movie_engine_prev_post_obj->ID),
        'thumbnail' => $movie_engine_prev_thumb
    ];
}

if (!empty($movie_engine_episode_nav_data)) {
    wp_add_inline_script('movie-engine', 'window.movieEngineEpisodes = ' . wp_json_encode($movie_engine_episode_nav_data) . ';');
}
$movie_engine_player_settings_val = get_option('movie_engine_player_settings', []);
if (!empty($movie_engine_player_settings_val['movie_engine_show_playlist_btn']) || !empty($movie_engine_player_settings_val['show_playlist_btn'])) {
    $movie_engine_seasons_query = get_posts([
        'post_type' => 'movie_engine_season',
        // phpcs:ignore WordPress.DB.SlowDBQuery
        'meta_query' => [
            ['key' => '_movie_engine_series_id', 'value' => $movie_engine_series_id]
        ],
        'posts_per_page' => -1,
        'orderby' => 'meta_value_num',
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        'meta_key' => '_movie_engine_season_number',
        'order' => 'ASC'
    ]);

    $movie_engine_playlist_data = [
        'series_id' => $movie_engine_series_id,
        'series_title' => get_the_title($movie_engine_series_id),
        'series_poster' => get_the_post_thumbnail_url($movie_engine_series_id, 'medium'),
        'current_episode_id' => $movie_engine_post_id,
        'seasons' => []
    ];

    foreach ($movie_engine_seasons_query as $movie_engine_season_post) {
        $movie_engine_season_number = get_post_meta($movie_engine_season_post->ID, '_movie_engine_season_number', true);

        $movie_engine_episodes_query = get_posts([
            'post_type' => 'movie_engine_episode',
            // 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_season_number]
            ],
            'posts_per_page' => -1,
            'orderby' => 'meta_value_num',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            'meta_key' => '_movie_engine_episode_number',
            'order' => 'ASC'
        ]);

        $movie_engine_episodes_list = [];
        foreach ($movie_engine_episodes_query as $movie_engine_ep_post) {
            $movie_engine_ep_number_val = get_post_meta($movie_engine_ep_post->ID, '_movie_engine_episode_number', true);
            $movie_engine_ep_runtime_val = get_post_meta($movie_engine_ep_post->ID, '_movie_engine_runtime', true);

            $movie_engine_episodes_list[] = [
                'id' => $movie_engine_ep_post->ID,
                'title' => $movie_engine_ep_post->post_title,
                'episode_number' => $movie_engine_ep_number_val,
                'url' => esc_url(get_permalink($movie_engine_ep_post->ID)),
                'thumbnail' => get_the_post_thumbnail_url($movie_engine_ep_post->ID, 'medium'),
                'runtime' => $movie_engine_ep_runtime_val,
                'description' => wp_trim_words($movie_engine_ep_post->post_content, 20, '...')
            ];
        }

        $movie_engine_playlist_data['seasons'][] = [
            'season_number' => $movie_engine_season_number,
            'episodes' => $movie_engine_episodes_list
        ];
    }

    if (!empty($movie_engine_playlist_data['seasons'])) {
        wp_add_inline_script('movie-engine', 'window.movieEnginePlaylist = ' . wp_json_encode($movie_engine_playlist_data) . ';');
    }
}
