<?php
use Elementor\Widget_Base;
use Elementor\Controls_Manager;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class skill_info_post_Widget extends Widget_Base {
    // Widget slug
    public function get_name() {
        return 'skill_info_post_widget';
    }
    // Widget title
    public function get_title() {
        return esc_html__('اطلاعات نوشته', 'skill');
    }
    // Widget icon
    public function get_icon() {
        return 'eicon-info-circle';
    }
    // Widget category
    public function get_categories() {
        return ['skill-category'];
    }
    // Widget keywords
    public function get_keywords() {
        return ['اطلاعات', 'پست', 'نوشته', 'post info', 'meta'];
    }
    // Register widget controls (Farsi labels)
    protected function register_controls() {
        $this->start_controls_section(
            'section_style',
            [
                'label' => esc_html__('استایل', 'skill'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );
        $this->add_control(
            'box_bg_color',
            [
                'label' => esc_html__('رنگ پس‌زمینه باکس', 'skill'),
                'type' => Controls_Manager::COLOR,
                'default' => '#232432',
                'selectors' => [
                    '{{WRAPPER}} .skill-info-post-box, {{WRAPPER}} .skill-related-posts-box' => 'background-color: {{VALUE}};',
                ],
            ]
        );
        $this->add_control(
            'box_radius',
            [
                'label' => esc_html__('گردی گوشه باکس', 'skill'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => ['min' => 0, 'max' => 40],
                    '%' => ['min' => 0, 'max' => 50],
                ],
                'default' => ['unit' => 'px', 'size' => 18],
                'selectors' => [
                    '{{WRAPPER}} .skill-info-post-box, {{WRAPPER}} .skill-related-posts-box' => 'border-radius: {{SIZE}}{{UNIT}};',
                ],
            ]
        );
        $this->add_control(
            'text_color',
            [
                'label' => esc_html__('رنگ متن', 'skill'),
                'type' => Controls_Manager::COLOR,
                'default' => '#fff',
                'selectors' => [
                    '{{WRAPPER}} .skill-info-post-box, {{WRAPPER}} .skill-info-post-box a, {{WRAPPER}} .skill-related-posts-box, {{WRAPPER}} .skill-related-posts-box a' => 'color: {{VALUE}};',
                ],
            ]
        );
        $this->add_control(
            'icon_color',
            [
                'label' => esc_html__('رنگ آیکون', 'skill'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffb43a',
                'selectors' => [
                    '{{WRAPPER}} .skill-info-post-box i, {{WRAPPER}} .skill-related-posts-box i' => 'color: {{VALUE}};',
                ],
            ]
        );
        $this->end_controls_section();

        // Behavior: Sticky options
        $this->start_controls_section(
            'section_behavior',
            [
                'label' => esc_html__('رفتار', 'skill'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'sticky_enable',
            [
                'label' => esc_html__('باکس چسبنده', 'skill'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('روشن', 'skill'),
                'label_off' => esc_html__('خاموش', 'skill'),
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_responsive_control(
            'sticky_top',
            [
                'label' => esc_html__('فاصله از بالا', 'skill'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => ['min' => 0, 'max' => 200],
                ],
                'default' => ['unit' => 'px', 'size' => 20],
                'condition' => [
                    'sticky_enable' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();

        // Related posts options
        $this->start_controls_section(
            'section_related',
            [
                'label' => esc_html__('مقالات مرتبط', 'skill'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'related_enable',
            [
                'label' => esc_html__('نمایش باکس مرتبط', 'skill'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('بله', 'skill'),
                'label_off' => esc_html__('خیر', 'skill'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'related_title',
            [
                'label' => esc_html__('عنوان باکس', 'skill'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('مقالات مرتبط', 'skill'),
                'label_block' => true,
                'condition' => [ 'related_enable' => 'yes' ],
            ]
        );

        $this->add_control(
            'related_count',
            [
                'label' => esc_html__('تعداد نمایش', 'skill'),
                'type' => Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 10,
                'step' => 1,
                'default' => 4,
                'condition' => [ 'related_enable' => 'yes' ],
            ]
        );

        $this->end_controls_section();
    }
    // Render widget output
    protected function render() {
        // Only show on single post
        if (!is_singular('post')) {
            return;
        }
        // Get post info
        $settings = $this->get_settings_for_display();
        $sticky_style = '';
        $top_value = 20;
        if (isset($settings['sticky_enable']) && $settings['sticky_enable'] === 'yes') {
            if (isset($settings['sticky_top']) && is_array($settings['sticky_top']) && isset($settings['sticky_top']['size'])) {
                $top_value = (int) $settings['sticky_top']['size'];
            }
            $sticky_style = ' position: -webkit-sticky; position: sticky; top: ' . $top_value . 'px; display:block; align-self:flex-start;';
        }
        $date = skill_get_persian_post_date_conditional('j F Y');
        $author = get_the_author();
        $tags = get_the_tags();
        $categories = get_the_category();
        ?>
        <?php if (!empty($sticky_style)) : ?>
            <style>
                .elementor-element-<?php echo esc_attr( $this->get_id() ); ?>,
                .elementor-element-<?php echo esc_attr( $this->get_id() ); ?> > .elementor-widget-container {
                    position: -webkit-sticky;
                    position: sticky;
                    top: <?php echo (int) $top_value; ?>px;
                    align-self: flex-start;
                    overflow: visible !important;
                    z-index: 2;
                }
            </style>
        <?php endif; ?>
        <div class="skill-info-post-box" style="padding:2rem 1.5rem; margin:1.5rem 0; direction:rtl; box-shadow:0 4px 24px 0 rgba(0,0,0,0.10); display:inline-block; min-width:260px;<?php echo esc_attr($sticky_style); ?>">
            <div style="display:flex; flex-direction:column; gap:1.2rem;">
                <!-- Post Date -->
                <div style="display:flex; align-items:center; gap:0.7rem; font-size:1.08rem;">
                    <i class="fa fa-calendar-alt" aria-hidden="true"></i>
                    <span><?php echo esc_html__('تاریخ انتشار:', 'skill') . ' ' . esc_html($date); ?></span>
                </div>
                <!-- Post Author -->
                <div style="display:flex; align-items:center; gap:0.7rem; font-size:1.08rem;">
                    <i class="fa fa-user" aria-hidden="true"></i>
                    <span><?php echo esc_html__('نویسنده:', 'skill') . ' ' . esc_html($author); ?></span>
                </div>
                <!-- Post Tags -->
                <div style="display:flex; align-items:center; gap:0.7rem; font-size:1.08rem; flex-wrap:wrap;">
                    <i class="fa fa-tags" aria-hidden="true"></i>
                    <span><?php echo esc_html__('برچسب‌ها:', 'skill'); ?></span>
                    <?php
                    if ($tags && is_array($tags)) {
                        foreach ($tags as $tag) {
                            echo '<a href="' . esc_url(get_tag_link($tag->term_id)) . '" style="margin-left:0.5rem; text-decoration:underline;">' . esc_html($tag->name) . '</a>';
                        }
                    } else {
                        echo '<span style="opacity:0.7;">' . esc_html__('بدون برچسب', 'skill') . '</span>';
                    }
                    ?>
                </div>
                <!-- Post Categories -->
                <div style="display:flex; align-items:center; gap:0.7rem; font-size:1.08rem; flex-wrap:wrap;">
                    <i class="fa fa-folder-open" aria-hidden="true"></i>
                    <span><?php echo esc_html__('دسته‌بندی:', 'skill'); ?></span>
                    <?php
                    if ($categories && is_array($categories)) {
                        foreach ($categories as $cat) {
                            echo '<a href="' . esc_url(get_category_link($cat->term_id)) . '" style="margin-left:0.5rem; text-decoration:underline;">' . esc_html($cat->name) . '</a>';
                        }
                    } else {
                        echo '<span style="opacity:0.7;">' . esc_html__('بدون دسته', 'skill') . '</span>';
                    }
                    ?>
                </div>
            </div>
        </div>
        <?php
        // Related posts box
        if ( isset($settings['related_enable']) && $settings['related_enable'] === 'yes' ) {
            $related_count = !empty($settings['related_count']) ? (int) $settings['related_count'] : 4;

            $current_id = get_the_ID();
            $tag_ids = [];
            if ($tags && is_array($tags)) {
                foreach ($tags as $t) { $tag_ids[] = (int) $t->term_id; }
            }
            $cat_ids = [];
            if ($categories && is_array($categories)) {
                foreach ($categories as $c) { $cat_ids[] = (int) $c->term_id; }
            }

            $tax_query = [];
            if (!empty($tag_ids)) {
                $tax_query[] = [
                    'taxonomy' => 'post_tag',
                    'field'    => 'term_id',
                    'terms'    => $tag_ids,
                ];
            } elseif (!empty($cat_ids)) {
                $tax_query[] = [
                    'taxonomy' => 'category',
                    'field'    => 'term_id',
                    'terms'    => $cat_ids,
                ];
            }

            $args = [
                'post_type'           => 'post',
                'posts_per_page'      => $related_count,
                'post__not_in'        => [$current_id],
                'ignore_sticky_posts' => true,
                'tax_query'           => $tax_query,
            ];

            $rel = new \WP_Query($args);
            if ($rel->have_posts()) : ?>
                <div class="skill-related-posts-box" style="padding:1.5rem; margin:1.5rem 0; direction:rtl; box-shadow:0 4px 24px 0 rgba(0,0,0,0.10); display:block; min-width:260px;">
                    <div style="display:flex; flex-direction:column; gap:1rem;">
                        <div style="display:flex; align-items:center; gap:0.6rem; font-size:1.08rem;">
                            <i class="fa fa-link" aria-hidden="true"></i>
                            <span><?php echo esc_html( !empty($settings['related_title']) ? $settings['related_title'] : esc_html__('مقالات مرتبط', 'skill') ); ?></span>
                        </div>
                        <ul style="list-style:none; padding:0; margin:0; display:flex; flex-direction:column; gap:0.8rem;">
                            <?php while ($rel->have_posts()) : $rel->the_post(); ?>
                                <li style="display:flex; align-items:center; gap:0.8rem;">
                                    <a href="<?php echo esc_url( get_permalink() ); ?>" style="display:flex; align-items:center; gap:0.8rem; text-decoration:underline;">
                                        <?php if ( has_post_thumbnail() ) : ?>
                                            <?php echo get_the_post_thumbnail( get_the_ID(), 'thumbnail', ['style' => 'width:56px; height:56px; object-fit:cover; border-radius:8px; flex-shrink:0;'] ); ?>
                                        <?php else : ?>
                                            <span style="width:56px; height:56px; display:inline-flex; align-items:center; justify-content:center; background:rgba(255,255,255,0.08); border-radius:8px;">
                                                <i class="fa fa-file-alt" aria-hidden="true" style="opacity:0.7;"></i>
                                            </span>
                                        <?php endif; ?>
                                        <span><?php echo esc_html( get_the_title() ); ?></span>
                                    </a>
                                </li>
                            <?php endwhile; ?>
                        </ul>
                    </div>
                </div>
            <?php endif; wp_reset_postdata();
        }
        ?>
        <?php
    }
}