<?php

namespace MovieEngine\Widgets;

use WP_Widget;
use WP_Query;

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

/**
 * Recent Episodes Widget
 */
class RecentEpisodes extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'movie_engine_recent_episodes',
            esc_html__('MovieEngine: Recent Episodes', 'cine-movie-engine'),
            ['description' => esc_html__('Display a list of recently added episodes.', 'cine-movie-engine')]
        );
    }

    public function widget($args, $instance) {
        $title = ! empty($instance['title']) ? $instance['title'] : esc_html__('Recent Episodes', '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_episode',
            'posts_per_page' => $limit,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];

        $episode_query = new WP_Query($query_args);

        if ($episode_query->have_posts()) : ?>
            <div class="movie-engine-episodes-widget">
                <?php while ($episode_query->have_posts()) : $episode_query->the_post();
                    $series_id = get_post_meta(get_the_ID(), 'movie_engine_series_id', true);
                    $series_title = get_the_title($series_id);
                ?>
                    <div class="me-widget-item">
                        <a href="<?php the_permalink(); ?>" class="me-widget-link">
                            <div class="me-widget-info">
                                <span class="me-widget-title"><?php echo esc_html($series_title); ?></span>
                                <span class="me-widget-meta"><?php the_title(); ?></span>
                            </div>
                        </a>
                    </div>
                <?php endwhile;
                wp_reset_postdata(); ?>
            </div>
        <?php else : ?>
            <p><?php esc_html_e('No episodes 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__('Recent Episodes', '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 episodes 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;
    }
}
