<?php

namespace Calio\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use WP_Query;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Renders a query-driven post carousel with lightweight navigation controls.
 */
class PostCarouselWidget extends BaseWidget {
    public function get_name(): string { return 'calio-post-carousel'; }
    public function get_title(): string { return esc_html__('Post Carousel', 'calio-addon'); }
    public function get_icon(): string { return 'eicon-posts-carousel'; }
    public function get_style_depends(): array { return $this->resolve_widget_style_depends(); }
    public function get_script_depends(): array { return $this->resolve_widget_script_depends(); }

    /**
     * Adds query, layout and style controls for the carousel widget.
     */
    protected function register_controls(): void {
        $this->start_controls_section('query', ['label' => esc_html__('Query', 'calio-addon')]);
        $this->add_control('post_type', ['label' => esc_html__('Post Type', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'post', 'options' => $this->get_post_type_options()]);
        $this->add_control('posts_per_page', ['label' => esc_html__('Posts Per Page', 'calio-addon'), 'type' => Controls_Manager::NUMBER, 'default' => 6, 'min' => 1, 'max' => 18]);
        $this->add_control('categories', ['label' => esc_html__('Categories', 'calio-addon'), 'type' => Controls_Manager::SELECT2, 'multiple' => true, 'label_block' => true, 'options' => $this->get_category_options(), 'condition' => ['post_type' => 'post']]);
        $this->add_control('orderby', ['label' => esc_html__('Order By', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'date', 'options' => ['date' => esc_html__('Date', 'calio-addon'), 'title' => esc_html__('Title', 'calio-addon'), 'rand' => esc_html__('Random', 'calio-addon'), 'comment_count' => esc_html__('Comment Count', 'calio-addon')]]);
        $this->add_control('order', ['label' => esc_html__('Order', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'DESC', 'options' => ['DESC' => 'DESC', 'ASC' => 'ASC']]);
        $this->add_control('ignore_sticky', ['label' => esc_html__('Ignore Sticky Posts', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['post_type' => 'post']]);
        $this->end_controls_section();

        $this->start_controls_section('layout', ['label' => esc_html__('Layout', 'calio-addon')]);
        $this->add_control('skin', ['label' => esc_html__('Skin', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'cards', 'options' => ['cards' => esc_html__('Cards', 'calio-addon'), 'editorial' => esc_html__('Editorial', 'calio-addon')]]);
        $this->add_control('slides_desktop', ['label' => esc_html__('Slides Desktop', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => '3', 'options' => ['1' => '1', '2' => '2', '3' => '3', '4' => '4']]);
        $this->add_control('slides_tablet', ['label' => esc_html__('Slides Tablet', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => '2', 'options' => ['1' => '1', '2' => '2', '3' => '3']]);
        $this->add_control('slides_mobile', ['label' => esc_html__('Slides Mobile', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => '1', 'options' => ['1' => '1', '2' => '2']]);
        $this->add_control('image_ratio', ['label' => esc_html__('Image Ratio', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'landscape', 'options' => ['landscape' => esc_html__('Landscape', 'calio-addon'), 'square' => esc_html__('Square', 'calio-addon'), 'portrait' => esc_html__('Portrait', 'calio-addon'), 'auto' => esc_html__('Auto', 'calio-addon')]]);
        $this->add_control('show_image', ['label' => esc_html__('Show Image', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('show_category', ['label' => esc_html__('Show Category', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['post_type' => 'post']]);
        $this->add_control('show_meta', ['label' => esc_html__('Show Meta', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('show_author', ['label' => esc_html__('Show Author', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['show_meta' => 'yes']]);
        $this->add_control('show_date', ['label' => esc_html__('Show Date', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['show_meta' => 'yes']]);
        $this->add_control('show_excerpt', ['label' => esc_html__('Show Excerpt', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('excerpt_length', ['label' => esc_html__('Excerpt Length', 'calio-addon'), 'type' => Controls_Manager::NUMBER, 'default' => 16, 'min' => 5, 'max' => 50, 'condition' => ['show_excerpt' => 'yes']]);
        $this->add_control('show_button', ['label' => esc_html__('Show Button', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('button_text', ['label' => esc_html__('Button Text', 'calio-addon'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Read Story', 'calio-addon'), 'condition' => ['show_button' => 'yes']]);
        $this->add_control('show_arrows', ['label' => esc_html__('Show Arrows', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('show_dots', ['label' => esc_html__('Show Dots', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('autoplay', ['label' => esc_html__('Autoplay', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => '']);
        $this->add_control('autoplay_speed', ['label' => esc_html__('Autoplay Speed', 'calio-addon'), 'type' => Controls_Manager::NUMBER, 'default' => 3500, 'min' => 1500, 'max' => 10000, 'step' => 100, 'condition' => ['autoplay' => 'yes']]);
        $this->add_control('pause_on_hover', ['label' => esc_html__('Pause On Hover', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['autoplay' => 'yes']]);
        $this->add_control('pause_on_interaction', ['label' => esc_html__('Pause After Interaction', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes', 'condition' => ['autoplay' => 'yes']]);
        $this->add_control('center_mode', ['label' => esc_html__('Center Mode', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => '']);
        $this->add_control('peek_slides', ['label' => esc_html__('Peek Side Slides', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => '', 'condition' => ['center_mode' => 'yes']]);
        $this->add_control('highlight_active_slide', ['label' => esc_html__('Highlight Active Slide', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->end_controls_section();

        $this->start_controls_section('style_cards', ['label' => esc_html__('Cards', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_control('carousel_gap', ['label' => esc_html__('Gap', 'calio-addon'), 'type' => Controls_Manager::SLIDER, 'range' => ['px' => ['min' => 0, 'max' => 40]], 'selectors' => ['{{WRAPPER}} .calio-post-carousel' => '--calio-carousel-gap: {{SIZE}}{{UNIT}};']]);
        $this->add_style_heading('post_carousel_card_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('card_padding', esc_html__('Content Padding', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-content', 'padding');
        $this->add_dimensions_control('card_margin', esc_html__('Card Margin', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-card', 'margin');
        $this->add_dimensions_control('card_radius', esc_html__('Radius', 'calio-addon'), ['{{WRAPPER}} .calio-post-carousel-card', '{{WRAPPER}} .calio-post-carousel-media', '{{WRAPPER}} .calio-post-carousel-media img'], 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_style_heading('post_carousel_card_surface_heading', esc_html__('Background & Border States', 'calio-addon'));
        $this->start_controls_tabs('post_carousel_card_state_tabs');
        $this->start_controls_tab('post_carousel_card_state_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_background_type_control('post_carousel_card_bg_normal_group', '{{WRAPPER}} .calio-post-carousel-card');
        $this->add_border_paint_controls('post_carousel_card_border_normal', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-card');
        $this->end_controls_tab();
        $this->start_controls_tab('post_carousel_card_state_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_background_type_control('post_carousel_card_bg_hover_group', ['{{WRAPPER}} .calio-post-carousel-card:hover', '{{WRAPPER}} .calio-post-carousel-card.is-active-slide']);
        $this->add_border_paint_controls('post_carousel_card_border_hover', esc_html__('Border Color', 'calio-addon'), ['{{WRAPPER}} .calio-post-carousel-card:hover', '{{WRAPPER}} .calio-post-carousel-card.is-active-slide']);
        $this->end_controls_tab();
        $this->start_controls_tab('post_carousel_card_state_active', ['label' => esc_html__('Active', 'calio-addon')]);
        $this->add_background_type_control('post_carousel_card_bg_active_group', '{{WRAPPER}} .calio-post-carousel-card:focus-within');
        $this->add_border_paint_controls('post_carousel_card_border_active', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-card:focus-within');
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->add_style_heading('post_carousel_card_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'card_border', 'selector' => '{{WRAPPER}} .calio-post-carousel-card']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'card_shadow', 'selector' => '{{WRAPPER}} .calio-post-carousel-card']);
        $this->end_controls_section();

        $this->start_controls_section('style_title', ['label' => esc_html__('Title', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'title_typography', 'selector' => '{{WRAPPER}} .calio-post-carousel-title, {{WRAPPER}} .calio-post-carousel-title a']);
        $this->add_text_paint_controls('post_carousel_title', esc_html__('Color', 'calio-addon'), ['{{WRAPPER}} .calio-post-carousel-title', '{{WRAPPER}} .calio-post-carousel-title a']);
        $this->add_text_paint_controls('post_carousel_meta', esc_html__('Meta Color', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-meta');
        $this->add_text_paint_controls('post_carousel_excerpt', esc_html__('Excerpt Color', 'calio-addon'), '{{WRAPPER}} .calio-post-carousel-excerpt');
        $this->end_controls_section();

        $this->start_controls_section('style_nav', ['label' => esc_html__('Navigation', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_style_heading('post_carousel_nav_surface_heading', esc_html__('Background States', 'calio-addon'));
        $this->add_text_paint_controls('post_carousel_nav_text', esc_html__('Text Color', 'calio-addon'), ['{{WRAPPER}} .calio-post-carousel-arrow', '{{WRAPPER}} .calio-post-carousel-dot']);
        $this->add_background_type_control('post_carousel_nav_bg_group', ['{{WRAPPER}} .calio-post-carousel-arrow', '{{WRAPPER}} .calio-post-carousel-dot']);
        $this->add_background_type_control('post_carousel_nav_active_bg_group', ['{{WRAPPER}} .calio-post-carousel-dot.is-active', '{{WRAPPER}} .calio-post-carousel-arrow:hover']);
        $this->add_style_heading('post_carousel_nav_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'post_carousel_nav_border', 'selector' => '{{WRAPPER}} .calio-post-carousel-arrow, {{WRAPPER}} .calio-post-carousel-dot']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'post_carousel_nav_shadow', 'selector' => '{{WRAPPER}} .calio-post-carousel-arrow, {{WRAPPER}} .calio-post-carousel-dot']);
        $this->end_controls_section();
    }

    /**
     * Outputs a query-driven post carousel with lightweight controls.
     */
    protected function render(): void {
        $settings = $this->get_settings_for_display();
        $query = new WP_Query($this->build_query_args($settings));

        if (!$query->have_posts()) {
            echo '<div class="calio-post-carousel-empty">' . esc_html__('No posts found.', 'calio-addon') . '</div>';
            wp_reset_postdata();
            return;
        }

        $carousel_id = 'calio-post-carousel-' . $this->get_id();
        $classes = [
            'calio-post-carousel',
            'skin-' . sanitize_html_class((string) ($settings['skin'] ?? 'cards')),
            'ratio-' . sanitize_html_class((string) ($settings['image_ratio'] ?? 'landscape')),
        ];
        if (($settings['center_mode'] ?? '') === 'yes') { $classes[] = 'is-center-mode'; }
        if (($settings['peek_slides'] ?? '') === 'yes') { $classes[] = 'has-peek-slides'; }

        echo '<div id="' . esc_attr($carousel_id) . '" class="' . esc_attr(implode(' ', $classes)) . '" data-slides-desktop="' . esc_attr((string) ($settings['slides_desktop'] ?? '3')) . '" data-slides-tablet="' . esc_attr((string) ($settings['slides_tablet'] ?? '2')) . '" data-slides-mobile="' . esc_attr((string) ($settings['slides_mobile'] ?? '1')) . '" data-show-dots="' . esc_attr((string) ($settings['show_dots'] ?? 'yes')) . '" data-autoplay="' . esc_attr((string) ($settings['autoplay'] ?? '')) . '" data-autoplay-speed="' . esc_attr((string) ($settings['autoplay_speed'] ?? '3500')) . '" data-pause-on-hover="' . esc_attr((string) ($settings['pause_on_hover'] ?? 'yes')) . '" data-pause-on-interaction="' . esc_attr((string) ($settings['pause_on_interaction'] ?? 'yes')) . '" data-center-mode="' . esc_attr((string) ($settings['center_mode'] ?? '')) . '" data-highlight-active-slide="' . esc_attr((string) ($settings['highlight_active_slide'] ?? 'yes')) . '">';
        echo '<div class="calio-post-carousel-viewport">';
        echo '<div class="calio-post-carousel-track">';
        while ($query->have_posts()) {
            $query->the_post();
            $this->render_post_card($settings);
        }
        echo '</div>';
        echo '</div>';

        if (($settings['show_arrows'] ?? 'yes') === 'yes' || ($settings['show_dots'] ?? 'yes') === 'yes') {
            echo '<div class="calio-post-carousel-footer">';
            if (($settings['show_arrows'] ?? 'yes') === 'yes') {
                echo '<div class="calio-post-carousel-arrows">';
                echo '<button class="calio-post-carousel-arrow is-prev" type="button" aria-label="' . esc_attr__('Previous slide', 'calio-addon') . '">&larr;</button>';
                echo '<button class="calio-post-carousel-arrow is-next" type="button" aria-label="' . esc_attr__('Next slide', 'calio-addon') . '">&rarr;</button>';
                echo '</div>';
            }

            if (($settings['show_dots'] ?? 'yes') === 'yes') {
                echo '<div class="calio-post-carousel-dots" aria-label="' . esc_attr__('Carousel pagination', 'calio-addon') . '"></div>';
            }
            echo '</div>';
        }

        echo '</div>';

        wp_reset_postdata();
    }

    /**
     * Builds a safe query array from Elementor controls.
     *
     * @param array<string, mixed> $settings Widget settings.
     * @return array<string, mixed>
     */
    private function build_query_args(array $settings): array {
        $post_type = sanitize_key((string) ($settings['post_type'] ?? 'post'));
        $post_type_object = get_post_type_object($post_type);
        if (!$post_type_object || !$post_type_object->public || $post_type === 'attachment') {
            $post_type = 'post';
        }

        $orderby = sanitize_key((string) ($settings['orderby'] ?? 'date'));
        if (!in_array($orderby, ['date', 'title', 'rand', 'comment_count'], true)) {
            $orderby = 'date';
        }

        $order = strtoupper((string) ($settings['order'] ?? 'DESC'));
        if (!in_array($order, ['ASC', 'DESC'], true)) {
            $order = 'DESC';
        }

        $args = [
            'post_type' => $post_type,
            'posts_per_page' => max(1, min(18, (int) ($settings['posts_per_page'] ?? 6))),
            'orderby' => $orderby,
            'order' => $order,
            'post_status' => 'publish',
            'no_found_rows' => true,
        ];

        if ($post_type === 'post' && ($settings['ignore_sticky'] ?? 'yes') === 'yes') {
            $args['ignore_sticky_posts'] = true;
        }

        if ($post_type === 'post' && !empty($settings['categories']) && is_array($settings['categories'])) {
            $args['category__in'] = array_values(array_filter(array_map('absint', $settings['categories'])));
        }

        return $args;
    }

    /**
     * Prints a single post card inside the carousel track.
     *
     * @param array<string, mixed> $settings Widget settings.
     */
    private function render_post_card(array $settings): void {
        $show_image = ($settings['show_image'] ?? 'yes') === 'yes';
        $show_category = ($settings['show_category'] ?? 'yes') === 'yes' && get_post_type() === 'post';
        $show_meta = ($settings['show_meta'] ?? 'yes') === 'yes';
        $show_author = $show_meta && (($settings['show_author'] ?? 'yes') === 'yes');
        $show_date = $show_meta && (($settings['show_date'] ?? 'yes') === 'yes');
        $show_excerpt = ($settings['show_excerpt'] ?? 'yes') === 'yes';
        $show_button = ($settings['show_button'] ?? 'yes') === 'yes';
        $excerpt_length = max(5, min(50, (int) ($settings['excerpt_length'] ?? 16)));
        $button_text = trim((string) ($settings['button_text'] ?? esc_html__('Read Story', 'calio-addon')));

        echo '<article class="calio-post-carousel-card">';
        if ($show_image && has_post_thumbnail()) {
            echo '<a class="calio-post-carousel-media" href="' . esc_url(get_permalink()) . '">';
            echo wp_kses_post(get_the_post_thumbnail(get_the_ID(), 'large', ['loading' => 'lazy']));
            echo '</a>';
        }

        echo '<div class="calio-post-carousel-content">';
        if ($show_category) {
            $terms = get_the_terms(get_the_ID(), 'category');
            if (is_array($terms) && !empty($terms)) {
                echo '<div class="calio-post-carousel-category-row">';
                foreach (array_slice($terms, 0, 2) as $term) {
                    echo '<span class="calio-post-carousel-category">' . esc_html($term->name) . '</span>';
                }
                echo '</div>';
            }
        }

        if ($show_meta && ($show_author || $show_date)) {
            echo '<div class="calio-post-carousel-meta">';
            if ($show_author) {
                echo '<span class="calio-post-carousel-meta-item">' . esc_html(get_the_author()) . '</span>';
            }
            if ($show_date) {
                echo '<span class="calio-post-carousel-meta-item">' . esc_html(get_the_date()) . '</span>';
            }
            echo '</div>';
        }

        echo '<h3 class="calio-post-carousel-title"><a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_title()) . '</a></h3>';

        if ($show_excerpt) {
            echo '<div class="calio-post-carousel-excerpt">' . esc_html(wp_trim_words(wp_strip_all_tags(get_the_excerpt()), $excerpt_length)) . '</div>';
        }

        if ($show_button && $button_text !== '') {
            echo '<a class="calio-post-carousel-button" href="' . esc_url(get_permalink()) . '">' . esc_html($button_text) . '</a>';
        }

        echo '</div>';
        echo '</article>';
    }

    /**
     * Returns public post types that make sense in a content carousel.
     *
     * @return array<string, string>
     */
    private function get_post_type_options(): array {
        $options = [];
        foreach (get_post_types(['public' => true], 'objects') as $post_type) {
            if ($post_type->name === 'attachment') {
                continue;
            }

            $options[$post_type->name] = $post_type->labels->singular_name;
        }

        return $options;
    }

    /**
     * Returns category options for post filtering.
     *
     * @return array<int, string>
     */
    private function get_category_options(): array {
        $options = [];
        $terms = get_terms(['taxonomy' => 'category', 'hide_empty' => false]);
        if (is_wp_error($terms) || !is_array($terms)) {
            return $options;
        }

        foreach ($terms as $term) {
            $options[(int) $term->term_id] = $term->name;
        }

        return $options;
    }
}

