<?php

namespace MovieEngine\Widgets;

use WP_Widget;
use WP_Query;

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

/**
 * Top Rated Movies Widget
 */
class TopRatedMovies extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'movie_engine_top_rated',
            esc_html__('MovieEngine: Top Rated', 'cine-movie-engine'),
            ['description' => esc_html__('Display a list of top rated movies/series.', 'cine-movie-engine')]
        );
    }

    public function widget($args, $instance) {
        $title = ! empty($instance['title']) ? $instance['title'] : esc_html__('Top Rated Content', 'cine-movie-engine');
        $limit = ! empty($instance['limit']) ? intval($instance['limit']) : 5;
        $type = ! empty($instance['type']) ? $instance['type'] : 'all';

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['before_widget'];
        if ($title) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $args['before_title'] . apply_filters('widget_title', $title) . $args['after_title'];
        }

        $post_types = ($type === 'all') ? ['movie_engine_movie', 'movie_engine_series'] : $type;

        $query_args = [
            'post_type'      => $post_types,
            'posts_per_page' => $limit,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            'meta_key'       => '_movie_engine_rating',
            'orderby'        => 'meta_value_num',
            'order'          => 'DESC',
        ];

        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        $rated_query = new WP_Query($query_args);

        if ($rated_query->have_posts()) : ?>
            <div class="movie-engine-rated-widget">
                <?php while ($rated_query->have_posts()) : $rated_query->the_post();
                    $rating = get_post_meta(get_the_ID(), '_movie_engine_rating', true);
                    $rating = $rating ? number_format($rating, 1) : 'N/A';
                ?>
                    <div class="me-widget-item">
                        <a href="<?php the_permalink(); ?>" class="me-widget-link">
                            <div class="me-widget-poster">
                                <?php if (has_post_thumbnail()) : ?>
                                    <?php the_post_thumbnail('thumbnail'); ?>
                                <?php endif; ?>
                            </div>
                            <div class="me-widget-info">
                                <span class="me-widget-title"><?php the_title(); ?></span>
                                <div class="me-widget-rating">
                                    <i class="fa-solid fa-star"></i>
                                    <span><?php echo esc_html($rating); ?></span>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endwhile;
                wp_reset_postdata(); ?>
            </div>
        <?php else : ?>
            <p><?php esc_html_e('No rated content found.', 'cine-movie-engine'); ?></p>
        <?php endif;

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = ! empty($instance['title']) ? $instance['title'] : esc_html__('Top Rated Content', 'cine-movie-engine');
        $limit = ! empty($instance['limit']) ? intval($instance['limit']) : 5;
        $type = ! empty($instance['type']) ? $instance['type'] : 'all';
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'cine-movie-engine'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label><?php esc_html_e('Content Type:', 'cine-movie-engine'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('type')); ?>" name="<?php echo esc_attr($this->get_field_name('type')); ?>">
                <option value="all" <?php selected($type, 'all'); ?>><?php esc_html_e('All Content', 'cine-movie-engine'); ?></option>
                <option value="movie_engine_movie" <?php selected($type, 'movie_engine_movie'); ?>><?php esc_html_e('Movies Only', 'cine-movie-engine'); ?></option>
                <option value="movie_engine_series" <?php selected($type, 'movie_engine_series'); ?>><?php esc_html_e('TV Series Only', 'cine-movie-engine'); ?></option>
            </select>
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('limit')); ?>"><?php esc_html_e('Limit:', 'cine-movie-engine'); ?></label>
            <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('limit')); ?>" name="<?php echo esc_attr($this->get_field_name('limit')); ?>" type="number" step="1" min="1" value="<?php echo esc_attr($limit); ?>" size="3">
        </p>
<?php
    }

    public function update($new_instance, $old_instance) {
        $instance = [];
        $instance['title'] = (! empty($new_instance['title'])) ? wp_strip_all_tags($new_instance['title']) : '';
        $instance['limit'] = (! empty($new_instance['limit'])) ? intval($new_instance['limit']) : 5;
        $instance['type'] = (! empty($new_instance['type'])) ? sanitize_text_field($new_instance['type']) : 'all';
        return $instance;
    }
}
