<?php

/**
 * Advanced Hero Shortcode Template
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/global/hero.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 MovieEngine
 */

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

if (empty($items)) {
    return;
}

$hero_id        = 'me-hero-' . wp_generate_password(4, false);
$autoplay       = filter_var($atts['autoplay'], FILTER_VALIDATE_BOOLEAN);
$autoplay_speed = intval($atts['autoplay_speed']);
$loop           = filter_var($atts['loop'], FILTER_VALIDATE_BOOLEAN);
$pause_on_hover = filter_var($atts['pause_on_hover'], FILTER_VALIDATE_BOOLEAN);
$custom_class   = !empty($atts['custom_class']) ? ' ' . esc_attr($atts['custom_class']) : '';
$desc_length    = isset($atts['description_length']) ? max(10, min(100, intval($atts['description_length']))) : 28;
$style          = $atts['style'] ?? 'style1';
$show_nav       = filter_var($atts['show_nav'], FILTER_VALIDATE_BOOLEAN);
$show_dots      = filter_var($atts['show_dots'], FILTER_VALIDATE_BOOLEAN);
$show_imdb      = filter_var($atts['show_imdb_badge'] ?? 'true', FILTER_VALIDATE_BOOLEAN);
$is_fullwidth   = filter_var($atts['fullwidth'] ?? 'false', FILTER_VALIDATE_BOOLEAN);
$container_class = $is_fullwidth ? 'movie-engine-container-fluid me-px-6' : 'movie-engine-container';
?>
<div id="<?php echo esc_attr($hero_id); ?>"
    class="movie-engine-hero-section movie-engine-plugin movie-engine-slider-enabled me-hero-slider-wrap me-hero-<?php echo esc_attr($style); ?><?php echo esc_attr($custom_class); ?>"
    style="--me-hero-height: <?php echo esc_attr($atts['height']); ?>;"
    data-autoplay="<?php echo $autoplay ? 'true' : 'false'; ?>"
    data-speed="<?php echo esc_attr($autoplay_speed); ?>"
    data-loop="<?php echo $loop ? 'true' : 'false'; ?>"
    data-pause="<?php echo $pause_on_hover ? 'true' : 'false'; ?>"
    data-nav="<?php echo $show_nav ? 'true' : 'false'; ?>"
    data-dots="<?php echo $show_dots ? 'true' : 'false'; ?>">

    <div class="me-hero-slider movie-engine-items-grid">
        <?php
        global $post;
        foreach ($items as $index => $item_post) :
            $post = $item_post;
            setup_postdata($post);
            $post_id = $post->ID;

            $backdrop = get_post_meta($post_id, '_movie_engine_backdrop_url', true);
            if (! $backdrop) {
                $backdrop = get_the_post_thumbnail_url($post_id, 'full');
            }
            $rating       = get_post_meta($post_id, '_movie_engine_rating', true);
            $runtime      = get_post_meta($post_id, '_movie_engine_runtime', true);
            $certification = get_post_meta($post_id, '_movie_engine_certification', true);
            $trailer      = get_post_meta($post_id, '_movie_engine_trailer', true);
            $release_date = get_post_meta($post_id, '_movie_engine_release_date', true);
            $release_year = $release_date ? gmdate('Y', strtotime($release_date)) : '';
            if (!$release_year) {
                $release_year = get_post_meta($post_id, '_movie_engine_year', true);
            }

            // Genres
            $genre_terms = get_the_terms($post_id, 'movie_engine_genre');
            $genre_names = [];
            if ($genre_terms && !is_wp_error($genre_terms)) {
                $top_genres = array_slice($genre_terms, 0, 3);
                foreach ($top_genres as $term) {
                    $genre_names[] = esc_html($term->name);
                }
            }
            $genres_clean = implode(' • ', $genre_names);
            $eyebrow_text = !empty($genre_names) ? $genre_names[0] : '';

            // Duration
            $duration = '';
            if ($runtime) {
                $hours    = floor($runtime / 60);
                $min      = $runtime % 60;
                $duration = ($hours > 0 ? $hours . 'h ' : '') . ($min > 0 ? $min . 'm' : '');
            }

            $cast_meta = get_post_meta($post_id, '_movie_engine_cast', true);
            $cast_names = [];
            if (!empty($cast_meta) && is_array($cast_meta)) {
                $starring_limit = isset($atts['starring_limit']) ? intval($atts['starring_limit']) : 6;
                $top_cast = array_slice($cast_meta, 0, $starring_limit);
                foreach ($top_cast as $actor) {
                    $actor_name = $actor['name'] ?? '';
                    $actor_id   = $actor['id'] ?? 0;
                    if ($actor_id && get_post_status($actor_id)) {
                        $cast_names[] = '<a href="' . esc_url(get_permalink($actor_id)) . '">' . esc_html(get_the_title($actor_id)) . '</a>';
                    } elseif ($actor_name) {
                        $cast_names[] = esc_html($actor_name);
                    }
                }
            }

            // Title length class
            $raw_title      = get_the_title();
            $title_len      = mb_strlen($raw_title);
            $title_len_attr = $title_len >= 35 ? 'xlong' : ($title_len >= 20 ? 'long' : 'short');
        ?>
            <div class="me-hero-item" data-index="<?php echo esc_attr($index); ?>">
                <div class="me-hero-bg" style="background-image: url('<?php echo esc_url($backdrop); ?>');" aria-hidden="true"></div>
                <div class="me-hero-overlay" aria-hidden="true"></div>

                <div class="<?php echo esc_attr($container_class); ?>">
                    <div class="me-hero-content">
                        <div class="me-hero-content-inner<?php echo $index === 0 ? ' me-hero-content-animate' : ''; ?>">

                            <?php if ($eyebrow_text) : ?>
                                <div class="me-hero-eyebrow"><?php echo esc_html($eyebrow_text); ?></div>
                            <?php endif; ?>

                            <<?php echo ($index === 0) ? 'h1' : 'h2'; ?> class="me-hero-title me-text-image" data-title-len="<?php echo esc_attr($title_len_attr); ?>">
                                <a href="<?php the_permalink(); ?>"><?php echo esc_html($raw_title); ?></a>
                            </<?php echo ($index === 0) ? 'h1' : 'h2'; ?>>

                            <div class="me-hero-meta">
                                <?php if ($show_imdb && $rating && $rating > 0) : ?>
                                    <span class="me-hero-imdb-badge">
                                        <i class="fa-solid fa-star" aria-hidden="true"></i>
                                        <?php echo esc_html(number_format((float)$rating, 1)); ?>
                                    </span>
                                <?php endif; ?>

                                <?php if ($release_year) : ?>
                                    <span class="me-hero-year"><?php echo esc_html($release_year); ?></span>
                                <?php endif; ?>

                                <?php if ($duration) : ?>
                                    <span class="me-hero-duration">
                                        <i class="fa-regular fa-clock" aria-hidden="true"></i>
                                        <?php echo esc_html($duration); ?>
                                    </span>
                                <?php endif; ?>

                                <?php if ($certification) : ?>
                                    <span class="me-hero-cert"><?php echo esc_html($certification); ?></span>
                                <?php endif; ?>

                                <?php if ($genres_clean) : ?>
                                    <span class="me-hero-genres"><?php echo esc_html($genres_clean); ?></span>
                                <?php endif; ?>
                            </div>

                            <?php if (filter_var($atts['show_description'], FILTER_VALIDATE_BOOLEAN)) : ?>
                                <div class="me-hero-description">
                                    <p><?php echo esc_html(wp_trim_words(get_the_content(), $desc_length, '...')); ?></p>
                                </div>
                            <?php endif; ?>

                            <div class="movie-engine-hero-actions">
                                <div class="me-primary-actions">
                                    <?php
                                    $movie_engine_is_premium_val     = get_post_meta($post_id, '_movie_engine_is_premium', true);
                                    $movie_engine_is_premium_val     = ($movie_engine_is_premium_val === '1' || $movie_engine_is_premium_val === 'yes' || $movie_engine_is_premium_val === 'true' || $movie_engine_is_premium_val === true || $movie_engine_is_premium_val === 1);
                                    $movie_engine_user_id            = get_current_user_id();
                                    $movie_engine_has_access         = false;
                                    $movie_engine_requires_login     = false;

                                    $movie_engine_monetization_settings = get_option('movie_engine_monetization_settings', []);
                                    $movie_engine_paywall_enabled    = !empty($movie_engine_monetization_settings['movie_engine_enable_paywall']) || !empty($movie_engine_monetization_settings['enable_paywall']);
                                    $movie_engine_restriction_mode   = $movie_engine_monetization_settings['movie_engine_restriction_mode'] ?? ($movie_engine_monetization_settings['restriction_mode'] ?? 'premium');
                                    $movie_engine_preview_duration   = \MovieEngine\Payments\Membership::get_preview_duration();
                                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                                    $movie_engine_preview_as_user    = isset($_GET['preview_as_user']) && sanitize_text_field(wp_unslash($_GET['preview_as_user'])) == '1';

                                    $movie_engine_login_url  = home_url('/dashboard/');
                                    $movie_engine_post_id    = $post_id;
                                    $movie_engine_player_url = trailingslashit(get_permalink($post_id)) . 'player/';
                                    if (!get_option('permalink_structure')) {
                                        $movie_engine_player_url = add_query_arg('player', 1, get_permalink($post_id));
                                    }

                                    if (current_user_can('administrator') && !$movie_engine_preview_as_user) {
                                        $movie_engine_has_access = true;
                                    } elseif (!$movie_engine_paywall_enabled) {
                                        $movie_engine_has_access = true;
                                    } elseif (\MovieEngine\Payments\Membership::is_premium($movie_engine_user_id, $movie_engine_preview_as_user)) {
                                        $movie_engine_has_access = true;
                                    } elseif (!$movie_engine_preview_as_user && \MovieEngine\Payments\Membership::is_in_trial_period($movie_engine_user_id)) {
                                        $movie_engine_has_access = true;
                                    } elseif ($movie_engine_restriction_mode === 'partial' && $movie_engine_preview_duration > 0) {
                                        $movie_engine_has_access = true;
                                    } elseif ($movie_engine_restriction_mode === 'all') {
                                        if ($movie_engine_user_id) {
                                            if ($movie_engine_is_premium_val) {
                                                $movie_engine_has_access = \MovieEngine\Payments\PPV::has_access($movie_engine_user_id, $post_id);
                                            } else {
                                                $movie_engine_has_access = true;
                                            }
                                        } else {
                                            $movie_engine_requires_login = true;
                                        }
                                    } elseif ($movie_engine_restriction_mode === 'premium') {
                                        if (!$movie_engine_is_premium_val) {
                                            $movie_engine_has_access = true;
                                        } elseif ($movie_engine_user_id) {
                                            $movie_engine_has_access = \MovieEngine\Payments\PPV::has_access($movie_engine_user_id, $post_id);
                                        } else {
                                            $movie_engine_requires_login = true;
                                        }
                                    } else {
                                        $movie_engine_has_access = true;
                                    }
                                    ?>

                                    <?php if (filter_var($atts['show_play_button'], FILTER_VALIDATE_BOOLEAN)) : ?>
                                        <?php if ($movie_engine_has_access) : ?>
                                            <a href="<?php echo esc_url($movie_engine_player_url); ?>" class="movie-engine-btn movie-engine-btn-play" aria-label="<?php echo esc_attr($atts['play_button_text']); ?> <?php echo esc_attr($raw_title); ?>">
                                                <?php echo esc_html($atts['play_button_text']); ?>
                                                <span class="fa-solid fa-play" aria-hidden="true"></span>
                                            </a>
                                        <?php elseif ($movie_engine_requires_login && !$movie_engine_is_premium_val) : ?>
                                            <button type="button" class="movie-engine-btn movie-engine-btn-play movie-engine-login-required-btn"
                                                data-login-url="<?php echo esc_url($movie_engine_login_url); ?>"
                                                aria-label="<?php echo esc_attr($atts['play_button_text']); ?> <?php echo esc_attr($raw_title); ?> (<?php esc_attr_e('Login Required', 'cine-movie-engine'); ?>)">
                                                <?php echo esc_html($atts['play_button_text']); ?>
                                                <span class="fa-solid fa-play" aria-hidden="true"></span>
                                            </button>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <?php \MovieEngine\Utils\TemplateLoader::get_template_part('global/button-ppv', '', ['compact' => true, 'context' => 'hero']); ?>

                                    <?php if ($trailer && filter_var($atts['show_trailer'], FILTER_VALIDATE_BOOLEAN)) : ?>
                                        <a href="<?php echo esc_url($trailer); ?>"
                                            class="movie-engine-btn movie-engine-btn-secondary me-open-trailer"
                                            data-url="<?php echo esc_url($trailer); ?>"
                                            aria-label="<?php echo esc_attr($atts['trailer_button_text']); ?> <?php echo esc_attr($raw_title); ?>">
                                            <span class="fa-solid fa-play" aria-hidden="true"></span>
                                            <?php echo esc_html($atts['trailer_button_text']); ?>
                                        </a>
                                    <?php endif; ?>

                                    <?php if (filter_var($atts['show_watchlist'] ?? 'true', FILTER_VALIDATE_BOOLEAN)) :
                                        $movie_engine_is_logged_in_for_watchlist = is_user_logged_in();
                                        $movie_engine_is_in_watchlist = false;
                                        if ($movie_engine_is_logged_in_for_watchlist) {
                                            $movie_engine_is_in_watchlist = \MovieEngine\Frontend\Users\UserLibrary::in_watchlist(get_current_user_id(), $post_id);
                                        }
                                        $movie_engine_watchlist_btn_class = 'movie-engine-btn movie-engine-btn-secondary movie-engine-watchlist-btn' . ($movie_engine_is_in_watchlist ? ' active' : '');
                                        $movie_engine_watchlist_text = $movie_engine_is_in_watchlist ? esc_html__('Remove Watchlist', 'cine-movie-engine') : esc_html__('WATCH LATER', 'cine-movie-engine');
                                        $movie_engine_watchlist_icon = $movie_engine_is_in_watchlist ? 'fa-solid fa-check' : 'fa-solid fa-plus';
                                    ?>
                                        <button type="button" class="<?php echo esc_attr($movie_engine_watchlist_btn_class); ?>"
                                            data-post-id="<?php echo esc_attr($post_id); ?>"
                                            aria-label="<?php echo esc_attr($movie_engine_watchlist_text); ?> <?php echo esc_attr($raw_title); ?>"
                                            <?php if (!$movie_engine_is_logged_in_for_watchlist) : ?>data-login-url="<?php echo esc_url(home_url('/dashboard/')); ?>" <?php endif; ?>>
                                            <span class="movie-engine-watchlist-text"><?php echo esc_html($movie_engine_watchlist_text); ?></span>
                                            <span class="<?php echo esc_attr($movie_engine_watchlist_icon); ?>" aria-hidden="true"></span>
                                        </button>
                                    <?php endif; ?>
                                </div>

                                <div class="me-icon-actions">
                                    <?php
                                    \MovieEngine\Utils\TemplateLoader::get_template_part('global/actions-social', '', ['post_id' => $post_id]);
                                    \MovieEngine\Utils\TemplateLoader::get_template_part('global/button-playlist', '', ['post_id' => $post_id]);
                                    ?>
                                </div>
                            </div>

                            <?php if (filter_var($atts['show_meta'], FILTER_VALIDATE_BOOLEAN) && (!empty($cast_names) || $genres_clean)) : ?>
                                <div class="me-hero-extra-meta">
                                    <?php if (!empty($cast_names)) : ?>
                                        <div class="me-meta-item">
                                            <span class="label"><?php esc_html_e('Starring', 'cine-movie-engine'); ?></span>
                                            <span class="value"><?php echo \MovieEngine\Utils\Helpers::kses_post(implode(', ', $cast_names)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML 
                                                                ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($genres_clean) : ?>
                                        <div class="me-meta-item">
                                            <span class="label"><?php esc_html_e('Genres', 'cine-movie-engine'); ?></span>
                                            <span class="value"><?php echo esc_html($genres_clean); ?></span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>

                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach;
        wp_reset_postdata(); ?>
    </div>

    <?php if ($style === 'style2' || $style === 'style3') : ?>
        <div class="me-hero-thumbnails-wrapper">
            <div class="<?php echo esc_attr($container_class); ?>">

                <div class="me-thumb-nav-btns" aria-label="<?php esc_attr_e('Slide navigation', 'cine-movie-engine'); ?>">
                </div>

                <div class="me-hero-thumbnails-nav">
                    <div class="me-hero-thumbnails-list">
                        <?php foreach ($items as $index => $item_post) :
                            $poster = get_the_post_thumbnail_url($item_post->ID, 'medium');
                            if (!$poster) {
                                $poster = get_post_meta($item_post->ID, '_movie_engine_backdrop_url', true);
                            }
                            $active_class = ($index === 0) ? ' is-active' : '';
                        ?>
                            <div class="me-hero-thumb<?php echo esc_attr($active_class); ?>" data-index="<?php echo esc_attr($index); ?>">
                                <?php if ($poster) : ?>
                                    <img src="<?php echo esc_url($poster); ?>"
                                        alt="<?php echo esc_attr($item_post->post_title); ?>"
                                        loading="lazy">
                                <?php else : ?>
                                    <div class="me-thumb-placeholder" aria-hidden="true"></div>
                                <?php endif; ?>
                                <div class="me-thumb-overlay" aria-hidden="true"></div>
                                <div class="me-thumb-title"><?php echo esc_html($item_post->post_title); ?></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

            </div>
        </div>
    <?php endif; ?>
</div>