<?php

/**
 * The template for displaying all reviews for a movie/series
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/pages/single-reviews.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
}

get_header();

$movie_engine_post_id = get_the_ID();
$movie_engine_meta = get_post_meta($movie_engine_post_id);
$movie_engine_poster = get_the_post_thumbnail_url($movie_engine_post_id, 'large');
$movie_engine_rating_avg = $movie_engine_meta['_movie_engine_user_rating'][0] ?? '0';
$movie_engine_rating_count = $movie_engine_meta['_movie_engine_user_rating_count'][0] ?? '0';

$movie_engine_comments_args = array(
    'post_id' => $movie_engine_post_id,
    'status'  => 'approve',
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
    'meta_key' => 'movie_engine_rating'
);
$movie_engine_comments = get_comments($movie_engine_comments_args);

$movie_engine_star_counts = [
    5 => 0,
    4 => 0,
    3 => 0,
    2 => 0,
    1 => 0
];
$movie_engine_star_labels = [
    5 => range(9, 10),
    4 => range(7, 8),
    3 => range(5, 6),
    2 => range(3, 4),
    1 => range(1, 2)
];

foreach ($movie_engine_comments as $movie_engine_comment) {
    $movie_engine_rating_val = intval(get_comment_meta($movie_engine_comment->comment_ID, 'movie_engine_rating', true));
    if ($movie_engine_rating_val >= 9) $movie_engine_star_counts[5]++;
    elseif ($movie_engine_rating_val >= 7) $movie_engine_star_counts[4]++;
    elseif ($movie_engine_rating_val >= 5) $movie_engine_star_counts[3]++;
    elseif ($movie_engine_rating_val >= 3) $movie_engine_star_counts[2]++;
    elseif ($movie_engine_rating_val >= 1) $movie_engine_star_counts[1]++;
}
?>

<div class="movie-engine-reviews-page-wrapper">
    <div class="movie-engine-container-fluid">
        <div class="movie-engine-reviews-grid">
            <div class="movie-engine-reviews-sidebar">
                <div class="movie-engine-poster-mini">
                    <img src="<?php echo esc_url($movie_engine_poster); ?>" alt="<?php the_title_attribute(); ?>">
                    <div class="movie-engine-poster-rating-badge">
                        <span class="fa-solid fa-star" aria-hidden="true"></span>
                        <span><?php echo esc_html($movie_engine_rating_avg); ?></span>
                    </div>
                </div>

                <div class="movie-engine-sidebar-content">
                    <div class="movie-engine-movie-meta">
                        <?php
                        $movie_engine_genres = get_the_term_list($movie_engine_post_id, 'movie_engine_genre', '', ' ', '');

                        if (! empty($movie_engine_genres)) {
                            echo '<span class="genres">' . \MovieEngine\Utils\Helpers::kses_post($movie_engine_genres) . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
                        }
                        ?>
                    </div>
                    <h2 class="movie-engine-page-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    <div class="movie-engine-movie-desc">
                        <?php echo esc_html(wp_trim_words(get_the_content(), 30)); ?>
                    </div>

                    <div class="movie-engine-rating-summary-box">
                        <div class="movie-engine-score-header">
                            <span class="score"><?php echo number_format((float)$movie_engine_rating_avg, 2); ?></span>
                            <div class="stars-wrapper">
                                <div class="stars">
                                    <?php
                                    $movie_engine_stars_count = round($movie_engine_rating_avg / 2);
                                    for ($movie_engine_i = 1; $movie_engine_i <= 5; $movie_engine_i++) {
                                        $movie_engine_star_color = $movie_engine_i <= $movie_engine_stars_count ? '#ffb400' : '#444';
                                        echo '<span class="fa-solid fa-star" style="color: ' . esc_attr($movie_engine_star_color) . ';" aria-hidden="true"></span>';
                                    }
                                    ?>
                                </div>
                                <span class="sub-text"><?php esc_html_e('Based on individual rating', 'cine-movie-engine'); ?></span>
                            </div>
                        </div>

                        <div class="movie-engine-rating-bars">
                            <?php for ($movie_engine_i = 5; $movie_engine_i >= 1; $movie_engine_i--):
                                $movie_engine_count = $movie_engine_star_counts[$movie_engine_i];
                                $movie_engine_percent = $movie_engine_rating_count > 0 ? ($movie_engine_count / $movie_engine_rating_count) * 100 : 0;
                            ?>
                                <div class="movie-engine-bar-row">
                                    <span class="star-label"><?php echo esc_html($movie_engine_i); ?></span>
                                    <div class="bar-track">
                                        <div class="bar-fill" style="width: <?php echo esc_attr($movie_engine_percent); ?>%; background: <?php echo esc_attr(($movie_engine_i >= 4 ? '#46d369' : ($movie_engine_i >= 3 ? '#ffb400' : '#d2d6dc'))); ?>;"></div>
                                    </div>
                                    <span class="count-label"><?php echo esc_html($movie_engine_count); ?></span>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="movie-engine-reviews-list-col">
                <div class="movie-engine-reviews-header-flex">
                    <h2 class="movie-engine-section-heading">
                        <?php printf(
                            /* translators: %s: post title */
                            esc_html__('Reviews for %s', 'cine-movie-engine'),
                            esc_html(get_the_title())
                        ); ?>
                    </h2>
                    <a href="<?php the_permalink(); ?>" class="movie-engine-back-link"><?php esc_html_e('Back to Title', 'cine-movie-engine'); ?> &rarr;</a>
                </div>

                <div class="movie-engine-all-reviews-list movie-engine-ajax-container" data-action="movie_engine_fetch_reviews" data-post_id="<?php echo esc_attr($movie_engine_post_id); ?>">
                    <?php
                    $movie_engine_design_options = get_option('movie_engine_design_settings', []);
                    $movie_engine_reviews_per_page = !empty($movie_engine_design_options['archive_items_per_page']) ? intval($movie_engine_design_options['archive_items_per_page']) : (!empty($movie_engine_design_options['movie_engine_archive_items_per_page']) ? intval($movie_engine_design_options['movie_engine_archive_items_per_page']) : 20);
                    $movie_engine_reviews_per_page = max(1, $movie_engine_reviews_per_page);
                    $movie_engine_pagination_type = $movie_engine_design_options['pagination_type'] ?? ($movie_engine_design_options['movie_engine_pagination_type'] ?? 'numbers');
                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                    $movie_engine_current_page = max(1, get_query_var('paged'), get_query_var('reviews'), isset($_GET['me_paged']) ? absint($_GET['me_paged']) : 1);
                    $movie_engine_offset = ($movie_engine_current_page - 1) * $movie_engine_reviews_per_page;

                    $movie_engine_all_comments = get_comments([
                        'post_id'      => $movie_engine_post_id,
                        'status'       => 'approve',
                        'number'       => $movie_engine_reviews_per_page,
                        'offset'       => $movie_engine_offset,
                        'orderby'      => [
                            'comment_date' => 'DESC',
                            'comment_ID'   => 'DESC'
                        ],
                        'hierarchical' => false,
                    ]);

                    $movie_engine_total_comments = get_comments_number($movie_engine_post_id);
                    $movie_engine_total_pages = ceil($movie_engine_total_comments / $movie_engine_reviews_per_page);

                    echo '<ul class="movie-engine-review-list">';
                    if ($movie_engine_all_comments) {
                        foreach ($movie_engine_all_comments as $movie_engine_comment) {
                            $GLOBALS['comment'] = $movie_engine_comment;
                    ?>
                            <li class="movie-engine-review-item" data-debug-page="<?php echo esc_attr($movie_engine_current_page); ?>">
                                <div class="movie-engine-review-body">
                                    <div class="movie-engine-review-author">
                                        <?php echo get_avatar($movie_engine_comment, 50); ?>
                                    </div>
                                    <div class="movie-engine-review-content">
                                        <div class="movie-engine-review-meta">
                                            <div class="movie-engine-review-author-info">
                                                <cite class="fn"><?php echo esc_html(get_comment_author($movie_engine_comment)); ?></cite>
                                                <span class="movie-engine-review-date"><?php echo esc_html(get_comment_date('', $movie_engine_comment)); ?></span>
                                            </div>
                                            <div class="movie-engine-review-meta-right">
                                                <?php echo \MovieEngine\Frontend\Reviews::render_rating_html($movie_engine_comment); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- rating HTML is safe 
                                                ?>
                                            </div>
                                        </div>
                                        <div class="movie-engine-comment-text">
                                            <?php echo \MovieEngine\Utils\Helpers::kses_post(get_comment_text($movie_engine_comment)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML 
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </li>
                    <?php
                        }
                    } else {
                        echo '<p class="me-no-reviews">' . esc_html__('No reviews yet.', 'cine-movie-engine') . '</p>';
                    }
                    echo '</ul>';

                    if ($movie_engine_total_pages > 1) {
                        if ($movie_engine_pagination_type === 'load_more' || $movie_engine_pagination_type === 'infinite') {
                            if ($movie_engine_current_page < $movie_engine_total_pages) {
                                echo '<div id="movie-engine-pagination-' . esc_attr($movie_engine_post_id) . '" class="movie-engine-pagination" data-type="' . esc_attr($movie_engine_pagination_type) . '" data-max-pages="' . esc_attr($movie_engine_total_pages) . '" data-total-comments="' . esc_attr($movie_engine_total_comments) . '">';
                                echo '<button class="movie-engine-load-more-btn movie-engine-btn movie-engine-btn-primary" data-paged="' . esc_attr($movie_engine_current_page + 1) . '" data-total-pages="' . esc_attr($movie_engine_total_pages) . '">' . esc_html__('Load More', 'cine-movie-engine') . '</button>';
                                if ($movie_engine_pagination_type === 'infinite') {
                                    echo '<div class="movie-engine-infinite-trigger" aria-hidden="true"></div>';
                                }
                                echo '</div>';
                            }
                        } else {
                            $base_url = esc_url(add_query_arg('reviews', '999999999', get_permalink()));

                            echo '<nav class="movie-engine-pagination" aria-label="' . esc_attr('Reviews pagination', 'cine-movie-engine') . '">';
                            // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML, pagination params are int/controlled
                            echo \MovieEngine\Utils\Helpers::kses_post(paginate_links(array(
                                'base'      => str_replace('999999999', '%#%', $base_url),
                                'format'    => '',
                                'current'   => $movie_engine_current_page,
                                'total'     => $movie_engine_total_pages,
                                'prev_text' => '<span aria-hidden="true">&larr;</span> <span class="me-sr-only">' . esc_html__('Previous', 'cine-movie-engine') . '</span>',
                                'next_text' => '<span class="me-sr-only">' . esc_html__('Next', 'cine-movie-engine') . '</span> <span aria-hidden="true">&rarr;</span>',
                                'type'      => 'list',
                            )));
                            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
                            echo '</nav>';
                        }
                    }
                    ?>
                </div>

                <div class="movie-engine-add-review-cta">
                    <a href="<?php the_permalink(); ?>#respond" class="movie-engine-btn me-btn-primary"><?php esc_html_e('Write a Review', 'cine-movie-engine'); ?></a>
                </div>
            </div>

        </div>
    </div>
</div>

<?php get_footer(); ?>