<?php

namespace MovieEngine\Widgets;

use WP_Widget;

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

/**
 * Genres Widget
 */
class GenresWidget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'movie_engine_genres',
            esc_html__('MovieEngine: Genres Cloud', 'cine-movie-engine'),
            ['description' => esc_html__('Display a list or cloud of movie genres.', 'cine-movie-engine')]
        );
    }

    public function widget($args, $instance) {
        $title = ! empty($instance['title']) ? $instance['title'] : esc_html__('Browse by Genre', 'cine-movie-engine');

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

        $genres = get_terms([
            'taxonomy'   => 'movie_engine_genre',
            'hide_empty' => true,
        ]);

        if (! is_wp_error($genres) && ! empty($genres)) : ?>
            <div class="movie-engine-genres-widget">
                <?php foreach ($genres as $genre) : ?>
                    <a href="<?php echo esc_url(get_term_link($genre)); ?>" class="me-genre-tag">
                        <?php echo esc_html($genre->name); ?>
                        <span class="count">(<?php echo esc_html($genre->count); ?>)</span>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else : ?>
            <p><?php esc_html_e('No genres 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__('Browse by Genre', 'cine-movie-engine');
        ?>
        <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>
<?php
    }

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