<?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 category-driven post tabs for editorial and news-style layouts.
 */
class PostsTabWidget extends BaseWidget {
    public function get_name(): string { return 'calio-posts-tab'; }
    public function get_title(): string { return esc_html__('Posts Tab', 'calio-addon'); }
    public function get_icon(): string { return 'eicon-tabs'; }
    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 content and style controls for the posts tab widget.
     */
    protected function register_controls(): void {
        $this->start_controls_section('query', ['label' => esc_html__('Query', 'calio-addon')]);
        $this->add_control('show_latest_tab', ['label' => esc_html__('Show Latest Tab', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => 'yes']);
        $this->add_control('latest_tab_label', ['label' => esc_html__('Latest Tab Label', 'calio-addon'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Latest', 'calio-addon'), 'condition' => ['show_latest_tab' => 'yes']]);
        $this->add_control('categories', ['label' => esc_html__('Category Tabs', 'calio-addon'), 'type' => Controls_Manager::SELECT2, 'multiple' => true, 'label_block' => true, 'options' => $this->get_category_options()]);
        $this->add_control('posts_per_tab', ['label' => esc_html__('Posts Per Tab', 'calio-addon'), 'type' => Controls_Manager::NUMBER, 'default' => 4, 'min' => 1, 'max' => 12]);
        $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->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'), 'minimal' => esc_html__('Minimal', 'calio-addon')]]);
        $this->add_control('columns', ['label' => esc_html__('Columns', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => '2', 'options' => ['1' => '1', '2' => '2', '3' => '3']]);
        $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_meta', ['label' => esc_html__('Show Meta', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => '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' => 14, 'min' => 5, 'max' => 40, '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 More', 'calio-addon'), 'condition' => ['show_button' => 'yes']]);
        $this->add_control('tab_skin', ['label' => esc_html__('Tab Skin', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'pill', 'options' => ['pill' => esc_html__('Pill', 'calio-addon'), 'underline' => esc_html__('Underline', 'calio-addon'), 'card' => esc_html__('Card', 'calio-addon')]]);
        $this->add_control('panel_skin', ['label' => esc_html__('Panel Skin', 'calio-addon'), 'type' => Controls_Manager::SELECT, 'default' => 'soft', 'options' => ['none' => esc_html__('None', 'calio-addon'), 'soft' => esc_html__('Soft', 'calio-addon'), 'outline' => esc_html__('Outline', 'calio-addon')]]);
        $this->add_control('show_tab_counts', ['label' => esc_html__('Show Tab Counts', 'calio-addon'), 'type' => Controls_Manager::SWITCHER, 'return_value' => 'yes', 'default' => '']);
        $this->end_controls_section();

        $this->start_controls_section('style_tabs', ['label' => esc_html__('Tabs', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'tab_typography', 'selector' => '{{WRAPPER}} .calio-posts-tab-button']);
        $this->add_style_heading('posts_tab_button_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('posts_tab_button_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-button', 'padding');
        $this->add_dimensions_control('posts_tab_button_margin', esc_html__('Margin', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-button', 'margin');
        $this->add_dimensions_control('posts_tab_button_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-button', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_style_heading('posts_tab_button_surface_heading', esc_html__('Background & Border States', 'calio-addon'));
        $this->start_controls_tabs('posts_tab_button_state_tabs');
        $this->start_controls_tab('posts_tab_button_state_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_text_paint_controls('posts_tab_button_text_normal', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-button');
        $this->add_background_type_control('posts_tab_button_bg_normal_group', '{{WRAPPER}} .calio-posts-tab-button');
        $this->end_controls_tab();
        $this->start_controls_tab('posts_tab_button_state_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_text_paint_controls('posts_tab_button_text_hover', esc_html__('Text Color', 'calio-addon'), ['{{WRAPPER}} .calio-posts-tab-button:hover', '{{WRAPPER}} .calio-posts-tab-button:focus-visible']);
        $this->add_background_type_control('posts_tab_button_bg_hover_group', ['{{WRAPPER}} .calio-posts-tab-button:hover', '{{WRAPPER}} .calio-posts-tab-button:focus-visible']);
        $this->end_controls_tab();
        $this->start_controls_tab('posts_tab_button_state_active', ['label' => esc_html__('Active', 'calio-addon')]);
        $this->add_text_paint_controls('posts_tab_button_text_active', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-button.is-active');
        $this->add_background_type_control('posts_tab_button_bg_active_group', '{{WRAPPER}} .calio-posts-tab-button.is-active');
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->add_text_paint_controls('posts_tab_count_text', esc_html__('Count Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-count');
        $this->add_background_type_control('posts_tab_count_bg_group', '{{WRAPPER}} .calio-posts-tab-count');
        $this->add_indicator_paint_controls('posts_tab_indicator', esc_html__('Indicator Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab.tab-skin-underline .calio-posts-tab-button.is-active', '{{WRAPPER}} .calio-posts-tab.tab-skin-card .calio-posts-tab-button.is-active');
        $this->add_style_heading('posts_tab_button_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'posts_tab_button_border', 'selector' => '{{WRAPPER}} .calio-posts-tab-button']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'posts_tab_button_shadow', 'selector' => '{{WRAPPER}} .calio-posts-tab-button']);
        $this->end_controls_section();

        $this->start_controls_section('style_panel', ['label' => esc_html__('Panel', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_style_heading('posts_tab_panel_surface_heading', esc_html__('Background & Border', 'calio-addon'));
        $this->add_background_type_control('posts_tab_panel_bg_group', '{{WRAPPER}} .calio-posts-tab-panel');
        $this->add_border_paint_controls('posts_tab_panel_border', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-panel');
        $this->add_style_heading('posts_tab_panel_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'posts_tab_panel_border_group', 'selector' => '{{WRAPPER}} .calio-posts-tab-panel']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'posts_tab_panel_shadow', 'selector' => '{{WRAPPER}} .calio-posts-tab-panel']);
        $this->add_style_heading('posts_tab_panel_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('panel_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-panel', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_dimensions_control('panel_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-panel', 'padding');
        $this->add_dimensions_control('panel_margin', esc_html__('Margin', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-panel', 'margin');
        $this->end_controls_section();

        $this->start_controls_section('style_cards', ['label' => esc_html__('Cards', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_control('card_gap', ['label' => esc_html__('Gap', 'calio-addon'), 'type' => Controls_Manager::SLIDER, 'range' => ['px' => ['min' => 0, 'max' => 40]], 'selectors' => ['{{WRAPPER}} .calio-posts-tab-grid' => 'gap: {{SIZE}}{{UNIT}};']]);
        $this->add_style_heading('posts_tab_card_shape_heading', esc_html__('Shape', 'calio-addon'));
        $this->add_dimensions_control('card_radius', esc_html__('Radius', 'calio-addon'), ['{{WRAPPER}} .calio-posts-tab-card', '{{WRAPPER}} .calio-posts-tab-media', '{{WRAPPER}} .calio-posts-tab-media img'], 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_style_heading('posts_tab_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-posts-tab-card']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'posts_tab_card_shadow', 'selector' => '{{WRAPPER}} .calio-posts-tab-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-posts-tab-title, {{WRAPPER}} .calio-posts-tab-title a']);
        $this->add_text_paint_controls('posts_tab_title_text', esc_html__('Title Color', 'calio-addon'), ['{{WRAPPER}} .calio-posts-tab-title', '{{WRAPPER}} .calio-posts-tab-title a']);
        $this->add_text_paint_controls('posts_tab_meta_text', esc_html__('Meta Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-meta');
        $this->add_text_paint_controls('posts_tab_excerpt_text', esc_html__('Excerpt Color', 'calio-addon'), '{{WRAPPER}} .calio-posts-tab-excerpt');
        $this->end_controls_section();
    }

    /**
     * Outputs the posts tab wrapper and category panels.
     */
    protected function render(): void {
        $settings = $this->get_settings_for_display();
        $tabs = $this->get_tabs($settings);

        if (empty($tabs)) {
            echo '<div class="calio-posts-tab-empty">' . esc_html__('No tabs configured.', 'calio-addon') . '</div>';
            return;
        }

        $widget_id = 'calio-posts-tab-' . $this->get_id();
        $skin = sanitize_html_class((string) ($settings['skin'] ?? 'cards'));
        $columns = sanitize_html_class((string) ($settings['columns'] ?? '2'));

        $tab_skin = sanitize_html_class((string) ($settings['tab_skin'] ?? 'pill'));
        $panel_skin = sanitize_html_class((string) ($settings['panel_skin'] ?? 'soft'));
        $show_tab_counts = ($settings['show_tab_counts'] ?? '') === 'yes';

        echo '<div id="' . esc_attr($widget_id) . '" class="calio-posts-tab skin-' . esc_attr($skin) . ' cols-' . esc_attr($columns) . ' tab-skin-' . esc_attr($tab_skin) . ' panel-skin-' . esc_attr($panel_skin) . '">';
        echo '<div class="calio-posts-tab-nav" role="tablist">';
        foreach ($tabs as $index => $tab) {
            echo '<button class="calio-posts-tab-button' . ($index === 0 ? ' is-active' : '') . '" type="button" role="tab" data-target="' . esc_attr($widget_id . '-' . $tab['slug']) . '" aria-selected="' . esc_attr($index === 0 ? 'true' : 'false') . '">';
            echo '<span class="calio-posts-tab-label">' . esc_html($tab['label']) . '</span>';
            if ($show_tab_counts) {
                echo '<span class="calio-posts-tab-count">' . esc_html(number_format_i18n((int) $tab['count'])) . '</span>';
            }
            echo '</button>';
        }
        echo '</div>';

        foreach ($tabs as $index => $tab) {
            $panel_id = $widget_id . '-' . $tab['slug'];
            echo '<div id="' . esc_attr($panel_id) . '" class="calio-posts-tab-panel' . ($index === 0 ? ' is-active' : '') . '" role="tabpanel">';
            $this->render_tab_posts($settings, $tab);
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Renders posts for a single tab panel.
     *
     * @param array<string, mixed> $settings Widget settings.
     * @param array{slug: string, label: string, category_id: int} $tab Tab configuration.
     */
    private function render_tab_posts(array $settings, array $tab): void {
        $query = new WP_Query($this->build_query_args($settings, (int) $tab['category_id']));

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

        echo '<div class="calio-posts-tab-grid">';
        while ($query->have_posts()) {
            $query->the_post();
            $this->render_post_card($settings);
        }
        echo '</div>';

        wp_reset_postdata();
    }

    /**
     * Builds the query array for a tab.
     *
     * @param array<string, mixed> $settings Widget settings.
     * @return array<string, mixed>
     */
    private function build_query_args(array $settings, int $category_id = 0): array {
        $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',
            'posts_per_page' => max(1, min(12, (int) ($settings['posts_per_tab'] ?? 4))),
            'orderby' => $orderby,
            'order' => $order,
            'post_status' => 'publish',
            'no_found_rows' => true,
        ];

        if ($category_id > 0) {
            $args['category__in'] = [$category_id];
        }

        return $args;
    }

    /**
     * Prints a single post card.
     *
     * @param array<string, mixed> $settings Widget settings.
     */
    private function render_post_card(array $settings): void {
        $show_image = ($settings['show_image'] ?? 'yes') === 'yes';
        $show_meta = ($settings['show_meta'] ?? 'yes') === 'yes';
        $show_excerpt = ($settings['show_excerpt'] ?? 'yes') === 'yes';
        $show_button = ($settings['show_button'] ?? 'yes') === 'yes';
        $excerpt_length = max(5, min(40, (int) ($settings['excerpt_length'] ?? 14)));
        $button_text = trim((string) ($settings['button_text'] ?? esc_html__('Read More', 'calio-addon')));

        echo '<article class="calio-posts-tab-card">';
        if ($show_image && has_post_thumbnail()) {
            echo '<a class="calio-posts-tab-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-posts-tab-content">';
        if ($show_meta) {
            echo '<div class="calio-posts-tab-meta">';
            echo '<span class="calio-posts-tab-meta-item">' . esc_html(get_the_date()) . '</span>';
            echo '</div>';
        }

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

        if ($show_excerpt) {
            echo '<div class="calio-posts-tab-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-posts-tab-button-link" href="' . esc_url(get_permalink()) . '">' . esc_html($button_text) . '</a>';
        }
        echo '</div>';
        echo '</article>';
    }

    /**
     * Resolves tab labels from widget settings.
     *
     * @param array<string, mixed> $settings Widget settings.
     * @return array<int, array{slug: string, label: string, category_id: int, count: int}>
     */
    private function get_tabs(array $settings): array {
        $tabs = [];

        if (($settings['show_latest_tab'] ?? 'yes') === 'yes') {
            $tabs[] = [
                'slug' => 'latest',
                'label' => trim((string) ($settings['latest_tab_label'] ?? esc_html__('Latest', 'calio-addon'))),
                'category_id' => 0,
                'count' => (int) wp_count_posts('post')->publish,
            ];
        }

        if (!empty($settings['categories']) && is_array($settings['categories'])) {
            foreach (array_values(array_filter(array_map('absint', $settings['categories']))) as $category_id) {
                $term = get_term($category_id, 'category');
                if (!$term || is_wp_error($term)) {
                    continue;
                }

                $tabs[] = [
                    'slug' => sanitize_title($term->slug),
                    'label' => $term->name,
                    'category_id' => (int) $term->term_id,
                    'count' => (int) $term->count,
                ];
            }
        }

        return $tabs;
    }

    /**
     * Returns category options for tab selection.
     *
     * @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;
    }
}


