<?php

namespace MovieEngine\Widgets;

use WP_Widget;
use WP_Query;

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

/**
 * Trending Movies Widget
 */
class TrendingMovies extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'movie_engine_trending_movies',
            esc_html__('MovieEngine: Trending Movies', 'cine-movie-engine'),
            ['description' => esc_html__('Display a list of trending movies.', 'cine-movie-engine')]
        );
    }

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

        // 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'];
        }

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

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

        if ($movie_query->have_posts()) : ?>
            <div class="movie-engine-trending-widget">
                <?php while ($movie_query->have_posts()) : $movie_query->the_post(); ?>
                    <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>
                                <span class="me-widget-meta"><?php echo esc_html(get_post_meta(get_the_ID(), 'movie_engine_release_year', true)); ?></span>
                            </div>
                        </a>
                    </div>
                <?php endwhile;
                wp_reset_postdata(); ?>
            </div>
        <?php else : ?>
            <p><?php esc_html_e('No movies 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__('Trending Movies', 'cine-movie-engine');
        $limit = ! empty($instance['limit']) ? intval($instance['limit']) : 5;
        ?>
        <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 for="<?php echo esc_attr($this->get_field_id('limit')); ?>"><?php esc_html_e('Number of movies to show:', '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;
        return $instance;
    }
}
