<?php

/**
 * The template for displaying movie card in loops
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/loop/content-movie.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_ratio = $args['ratio'] ?? 'portrait';
$movie_engine_custom_ratio = $args['custom_ratio'] ?? '';

if (in_array($movie_engine_ratio, ['landscape', 'square', 'banner', 'custom'])) {
    $movie_engine_poster = get_post_meta($movie_engine_post_id, '_movie_engine_backdrop_url', true);
    if (!$movie_engine_poster) {
        $movie_engine_poster = get_the_post_thumbnail_url($movie_engine_post_id, 'large');
    }
} else {
    $movie_engine_poster = get_the_post_thumbnail_url($movie_engine_post_id, 'medium');
}

$movie_engine_card_style = '';
if ($movie_engine_ratio === 'custom' && !empty($movie_engine_custom_ratio)) {
    $movie_engine_card_style = 'style="--me-custom-ratio: ' . esc_attr($movie_engine_custom_ratio) . ';"';
}

$movie_engine_rating = get_post_meta($movie_engine_post_id, '_movie_engine_rating', true);
$movie_engine_years = get_the_terms($movie_engine_post_id, 'movie_engine_year');
$movie_engine_year = ($movie_engine_years && !is_wp_error($movie_engine_years)) ? $movie_engine_years[0]->name : '';
$movie_engine_post_type = get_post_type();
$movie_engine_quality_tax = ($movie_engine_post_type === 'movie_engine_series') ? 'movie_engine_tv_quality' : 'movie_engine_quality';
$movie_engine_qualities = get_the_terms($movie_engine_post_id, $movie_engine_quality_tax);
$movie_engine_quality = ($movie_engine_qualities && !is_wp_error($movie_engine_qualities)) ? $movie_engine_qualities[0]->name : '';

if ($movie_engine_post_type === 'movie_engine_series') {
    $movie_engine_type_label = esc_html__('TV Series', 'cine-movie-engine');
} elseif ($movie_engine_post_type === 'movie_engine_episode') {
    $movie_engine_ep_num = get_post_meta($movie_engine_post_id, '_movie_engine_episode_number', true);
    $movie_engine_type_label = $movie_engine_ep_num ? sprintf(
        /* translators: %s: episode number */
        esc_html__('Episode %s', 'cine-movie-engine'),
        $movie_engine_ep_num
    ) : esc_html__('Episode', 'cine-movie-engine');
} else {
    $movie_engine_type_label = esc_html__('Movie', 'cine-movie-engine');
}

$movie_engine_design = get_option('movie_engine_design_settings', []);
$movie_engine_show_year = isset($args['show_year']) ? $args['show_year'] : (isset($movie_engine_design['archive_show_year']) ? $movie_engine_design['archive_show_year'] : 1);
$movie_engine_show_rating = isset($args['show_rating']) ? $args['show_rating'] : (isset($movie_engine_design['archive_show_rating']) ? $movie_engine_design['archive_show_rating'] : 1);
$movie_engine_show_quality = isset($args['show_quality']) ? $args['show_quality'] : (isset($movie_engine_design['archive_show_quality']) ? $movie_engine_design['archive_show_quality'] : 1);
$movie_engine_is_pro = apply_filters('movie_engine_is_pro', false);
$movie_engine_show_type = isset($args['show_type']) ? $args['show_type'] : 1;
$movie_engine_show_price = $movie_engine_is_pro && (isset($args['show_price']) ? $args['show_price'] : 1);
$movie_engine_show_access_label = $movie_engine_is_pro && (isset($args['show_access_label']) ? $args['show_access_label'] : 1);

$movie_engine_payment_settings = get_option('movie_engine_payments_settings', []);
$movie_engine_currency = $movie_engine_payment_settings['movie_engine_currency'] ?? ($movie_engine_payment_settings['currency'] ?? 'USD');
$movie_engine_currency_symbol = $movie_engine_currency === 'USD' ? '$' : $movie_engine_currency;

$movie_engine_is_premium = (get_post_meta($movie_engine_post_id, '_movie_engine_is_premium', true) === '1');
$movie_engine_sale_price = get_post_meta($movie_engine_post_id, '_movie_engine_sale_price', true);
$movie_engine_rent_price = get_post_meta($movie_engine_post_id, '_movie_engine_rent_price', true);
$movie_engine_has_price = (floatval($movie_engine_sale_price) > 0 || floatval($movie_engine_rent_price) > 0);

$movie_engine_card_title_val = get_the_title();

$movie_engine_highlight_query_val = $args['highlight_query'] ?? ($args['movie_engine_highlight_query'] ?? '');

if (!empty($movie_engine_highlight_query_val)) {
    $movie_engine_card_title_val = preg_replace('/(' . preg_quote((string) $movie_engine_highlight_query_val, '/') . ')/i', '<mark>$1</mark>', (string) $movie_engine_card_title_val);
}
$movie_engine_style = $args['style'] ?? 'classic';
?>

<div class="movie-engine-movie-card me-card-<?php echo esc_attr($movie_engine_ratio); ?> me-style-<?php echo esc_attr($movie_engine_style); ?>" <?php echo $movie_engine_card_style; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
                                                                                                                                                ?>>
    <a href="<?php the_permalink(); ?>" class="movie-engine-card-poster" aria-label="<?php the_title_attribute(); ?>">
        <?php if ($movie_engine_poster) : ?>
            <img src="<?php echo esc_url($movie_engine_poster); ?>" alt="<?php the_title_attribute(); ?>">
        <?php else : ?>
            <div class="movie-engine-poster-placeholder">
                <span class="fa-solid fa-film" aria-hidden="true"></span>
            </div>
        <?php endif; ?>

        <?php if ($movie_engine_quality && $movie_engine_show_quality) : ?>
            <span class="movie-engine-card-quality"><?php echo esc_html($movie_engine_quality); ?></span>
        <?php endif; ?>

        <?php if ($args['show_badges'] ?? true) : ?>
            <?php \MovieEngine\Utils\Helpers::render_badges($movie_engine_post_id, 'card', $args); ?>
        <?php endif; ?>

        <?php if ($movie_engine_rating && $movie_engine_show_rating) : ?>
            <span class="movie-engine-card-rating">
                <span class="fa-solid fa-star star-icon" aria-hidden="true"></span>
                <?php echo esc_html($movie_engine_rating); ?>
            </span>
        <?php endif; ?>

        <div class="movie-engine-card-overlay">
            <span class="fa-solid fa-play" aria-hidden="true"></span>
        </div>

        <?php
        if (is_user_logged_in()) {
            $movie_engine_user_id = get_current_user_id();
            $movie_engine_progress = \MovieEngine\Frontend\Users\WatchHistory::get_progress($movie_engine_user_id, $movie_engine_post_id);

            if ($movie_engine_progress > 0) {
                $movie_engine_p_type = get_post_type($movie_engine_post_id);
                $movie_engine_duration = get_post_meta($movie_engine_post_id, '_movie_engine_duration_seconds', true);

                if (empty($movie_engine_duration)) {
                    if ($movie_engine_p_type === 'movie_engine_movie' || $movie_engine_p_type === 'movie_engine_series') {
                        $movie_engine_runtime = get_post_meta($movie_engine_post_id, '_movie_engine_runtime', true);
                        $movie_engine_duration = (!empty($movie_engine_runtime)) ? intval($movie_engine_runtime) * 60 : 7200;
                    } elseif ($movie_engine_p_type === 'movie_engine_episode') {
                        $movie_engine_episode_duration = get_post_meta($movie_engine_post_id, '_movie_engine_duration', true);
                        $movie_engine_duration = (!empty($movie_engine_episode_duration)) ? intval($movie_engine_episode_duration) : 2700;
                    }
                }

                if ($movie_engine_duration > 0) {
                    $movie_engine_percent = min(100, round(($movie_engine_progress / $movie_engine_duration) * 100));
                    if ($movie_engine_percent >= 1) {
                        echo '<div class="movie-engine-progress-bar">';
                        echo '<div class="movie-engine-progress-fill" style="width: ' . esc_attr($movie_engine_percent) . '%;"></div>';
                        echo '</div>';
                    }
                }
            }
        }
        ?>

        <?php
        /**
         * Hook: movie_engine_card_poster_end
         * Fires inside the card poster area, after all poster content.
         * Use this to inject custom overlays, labels, or PRO features.
         *
         * @param int $movie_engine_post_id The current post ID.
         */
        do_action('movie_engine_card_poster_end', $movie_engine_post_id);
        ?>
    </a>

    <div class="movie-engine-card-content">
        <h2 class="movie-engine-card-title">
            <a href="<?php the_permalink(); ?>"><?php echo \MovieEngine\Utils\Helpers::kses_post($movie_engine_card_title_val); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML ?></a>
        </h2>
        <div class="movie-engine-card-meta">
            <?php if ($movie_engine_year && $movie_engine_show_year) : ?>
                <span class="year"><?php echo esc_html($movie_engine_year); ?></span>
            <?php endif; ?>
            <?php if ($movie_engine_show_type) : ?>
                <span class="type"><?php echo esc_html($movie_engine_type_label); ?></span>
            <?php endif; ?>

            <?php if ($movie_engine_show_price && $movie_engine_has_price) :
                $display_price = $movie_engine_sale_price ? $movie_engine_sale_price : $movie_engine_rent_price;
            ?>
                <span class="me-card-price"><?php echo esc_html($movie_engine_currency_symbol) . esc_html(number_format($display_price, 2)); ?></span>
            <?php elseif ($movie_engine_show_access_label && ($args['show_free'] ?? false) && !$movie_engine_is_premium && !$movie_engine_has_price) : ?>
                <span class="me-card-access-free"><?php esc_html_e('FREE', 'cine-movie-engine'); ?></span>
            <?php elseif ($movie_engine_show_access_label && $movie_engine_is_premium) : ?>
                <span class="me-card-access-premium"><?php esc_html_e('PRO', 'cine-movie-engine'); ?></span>
            <?php endif; ?>
        </div>

        <?php
        /**
         * Hook: movie_engine_card_content_end
         * Fires at the end of the card content area, after the meta row.
         * Use this to inject pricing, rent buttons, or extra metadata.
         *
         * @param int $movie_engine_post_id The current post ID.
         */
        do_action('movie_engine_card_content_end', $movie_engine_post_id);
        ?>
    </div>
</div>