<?php
declare(strict_types=1);


/**
 * Elementor FAQ Widget with Auto Schema
 *
 * @package ProRank\Integrations\Elementor\Widgets
 */

namespace ProRank\SEO\Integrations\Elementor\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
use Elementor\Core\Kits\Documents\Tabs\Global_Colors;
use Elementor\Icons_Manager;

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




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

/**
 * FAQ widget for Elementor with automatic FAQPage schema
 */
class FAQWidget extends Widget_Base {

    /**
     * Get widget name
     */
    public function get_name(): string {
        return 'prorank-faq';
    }

    /**
     * Get widget title
     */
    public function get_title(): string {
        return __('FAQ with Schema', 'prorank-seo');
    }

    /**
     * Get widget icon
     */
    public function get_icon(): string {
        return 'eicon-accordion';
    }

    /**
     * Get widget categories
     */
    public function get_categories(): array {
        return ['prorank-seo'];
    }

    /**
     * Get widget keywords
     */
    public function get_keywords(): array {
        return ['faq', 'accordion', 'schema', 'seo', 'questions', 'answers', 'prorank'];
    }

    /**
     * Get script dependencies
     */
    public function get_script_depends(): array {
        return [];
    }

    /**
     * Register widget controls
     */
    protected function register_controls(): void {
        // Content Section - FAQ Items
        $this->start_controls_section(
            'section_faq_items',
            [
                'label' => __('FAQ Items', 'prorank-seo'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'question',
            [
                'label'       => __('Question', 'prorank-seo'),
                'type'        => Controls_Manager::TEXT,
                'default'     => __('What is your question?', 'prorank-seo'),
                'label_block' => true,
                'dynamic'     => [
                    'active' => true,
                ],
            ]
        );

        $repeater->add_control(
            'answer',
            [
                'label'   => __('Answer', 'prorank-seo'),
                'type'    => Controls_Manager::WYSIWYG,
                'default' => __('This is the answer to your question.', 'prorank-seo'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'faq_items',
            [
                'label'       => __('FAQ Items', 'prorank-seo'),
                'type'        => Controls_Manager::REPEATER,
                'fields'      => $repeater->get_controls(),
                'default'     => [
                    [
                        'question' => __('What is this FAQ about?', 'prorank-seo'),
                        'answer'   => __('This FAQ section helps answer common questions about your product or service.', 'prorank-seo'),
                    ],
                    [
                        'question' => __('How does the schema work?', 'prorank-seo'),
                        'answer'   => __('The FAQ schema is automatically generated and added to the page, helping your content appear as rich results in Google Search.', 'prorank-seo'),
                    ],
                ],
                'title_field' => '{{{ question }}}',
            ]
        );

        $this->end_controls_section();

        // Content Section - Settings
        $this->start_controls_section(
            'section_settings',
            [
                'label' => __('Settings', 'prorank-seo'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'layout',
            [
                'label'   => __('Layout', 'prorank-seo'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'accordion',
                'options' => [
                    'accordion' => __('Accordion (Collapsible)', 'prorank-seo'),
                    'list'      => __('List (Always Open)', 'prorank-seo'),
                ],
            ]
        );

        $this->add_control(
            'first_open',
            [
                'label'        => __('First Item Open', 'prorank-seo'),
                'type'         => Controls_Manager::SWITCHER,
                'label_on'     => __('Yes', 'prorank-seo'),
                'label_off'    => __('No', 'prorank-seo'),
                'return_value' => 'yes',
                'default'      => 'yes',
                'condition'    => [
                    'layout' => 'accordion',
                ],
            ]
        );

        $this->add_control(
            'enable_schema',
            [
                'label'        => __('Enable FAQPage Schema', 'prorank-seo'),
                'type'         => Controls_Manager::SWITCHER,
                'label_on'     => __('Yes', 'prorank-seo'),
                'label_off'    => __('No', 'prorank-seo'),
                'return_value' => 'yes',
                'default'      => 'yes',
                'description'  => __('Automatically adds FAQPage structured data for Google rich results', 'prorank-seo'),
            ]
        );

        $this->add_control(
            'icon_open',
            [
                'label'   => __('Open Icon', 'prorank-seo'),
                'type'    => Controls_Manager::ICONS,
                'default' => [
                    'value'   => 'fas fa-plus',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'layout' => 'accordion',
                ],
            ]
        );

        $this->add_control(
            'icon_close',
            [
                'label'   => __('Close Icon', 'prorank-seo'),
                'type'    => Controls_Manager::ICONS,
                'default' => [
                    'value'   => 'fas fa-minus',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'layout' => 'accordion',
                ],
            ]
        );

        $this->end_controls_section();

        // Style Section - Question
        $this->start_controls_section(
            'section_style_question',
            [
                'label' => __('Question', 'prorank-seo'),
                'tab'   => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'question_typography',
                'selector' => '{{WRAPPER}} .prorank-faq-question',
                'global'   => [
                    'default' => Global_Typography::TYPOGRAPHY_PRIMARY,
                ],
            ]
        );

        $this->add_control(
            'question_color',
            [
                'label'     => __('Color', 'prorank-seo'),
                'type'      => Controls_Manager::COLOR,
                'global'    => [
                    'default' => Global_Colors::COLOR_PRIMARY,
                ],
                'selectors' => [
                    '{{WRAPPER}} .prorank-faq-question' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'question_bg_color',
            [
                'label'     => __('Background Color', 'prorank-seo'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .prorank-faq-question' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'question_padding',
            [
                'label'      => __('Padding', 'prorank-seo'),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors'  => [
                    '{{WRAPPER}} .prorank-faq-question' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Style Section - Answer
        $this->start_controls_section(
            'section_style_answer',
            [
                'label' => __('Answer', 'prorank-seo'),
                'tab'   => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'answer_typography',
                'selector' => '{{WRAPPER}} .prorank-faq-answer',
                'global'   => [
                    'default' => Global_Typography::TYPOGRAPHY_TEXT,
                ],
            ]
        );

        $this->add_control(
            'answer_color',
            [
                'label'     => __('Color', 'prorank-seo'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .prorank-faq-answer' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'answer_bg_color',
            [
                'label'     => __('Background Color', 'prorank-seo'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .prorank-faq-answer' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'answer_padding',
            [
                'label'      => __('Padding', 'prorank-seo'),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors'  => [
                    '{{WRAPPER}} .prorank-faq-answer' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Style Section - Item
        $this->start_controls_section(
            'section_style_item',
            [
                'label' => __('FAQ Item', 'prorank-seo'),
                'tab'   => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'item_spacing',
            [
                'label'      => __('Spacing Between Items', 'prorank-seo'),
                'type'       => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range'      => [
                    'px' => [
                        'min' => 0,
                        'max' => 50,
                    ],
                ],
                'default'    => [
                    'size' => 10,
                    'unit' => 'px',
                ],
                'selectors'  => [
                    '{{WRAPPER}} .prorank-faq-item:not(:last-child)' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name'     => 'item_border',
                'selector' => '{{WRAPPER}} .prorank-faq-item',
            ]
        );

        $this->add_responsive_control(
            'item_border_radius',
            [
                'label'      => __('Border Radius', 'prorank-seo'),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors'  => [
                    '{{WRAPPER}} .prorank-faq-item' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name'     => 'item_box_shadow',
                'selector' => '{{WRAPPER}} .prorank-faq-item',
            ]
        );

        $this->end_controls_section();

        // Style Section - Icon
        $this->start_controls_section(
            'section_style_icon',
            [
                'label'     => __('Icon', 'prorank-seo'),
                'tab'       => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'layout' => 'accordion',
                ],
            ]
        );

        $this->add_control(
            'icon_color',
            [
                'label'     => __('Color', 'prorank-seo'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .prorank-faq-icon' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .prorank-faq-icon svg' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'icon_size',
            [
                'label'      => __('Size', 'prorank-seo'),
                'type'       => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range'      => [
                    'px' => [
                        'min' => 8,
                        'max' => 40,
                    ],
                ],
                'selectors'  => [
                    '{{WRAPPER}} .prorank-faq-icon' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .prorank-faq-icon svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render widget output
     */
    protected function render(): void {
        $settings = $this->get_settings_for_display();
        $faqs = $settings['faq_items'];
        $layout = $settings['layout'];
        $first_open = $settings['first_open'] === 'yes';
        $enable_schema = $settings['enable_schema'] === 'yes';

        if (empty($faqs)) {
            return;
        }

        $widget_id = $this->get_id();
        ?>
        <div class="prorank-faq-widget prorank-faq-<?php echo esc_attr($layout); ?>" data-layout="<?php echo esc_attr($layout); ?>">
            <?php foreach ($faqs as $index => $faq) :
                $is_open = ($layout === 'list') || ($first_open && $index === 0);
                $item_class = $is_open ? 'prorank-faq-item active' : 'prorank-faq-item';
                ?>
                <div class="<?php echo esc_attr($item_class); ?>">
                    <<?php echo $layout === 'accordion' ? 'button' : 'h3'; ?>
                        class="prorank-faq-question"
                        <?php if ($layout === 'accordion') : ?>
                            type="button"
                            aria-expanded="<?php echo $is_open ? 'true' : 'false'; ?>"
                            aria-controls="faq-answer-<?php echo esc_attr($widget_id . '-' . $index); ?>"
                        <?php endif; ?>
                    >
                        <span class="prorank-faq-question-text"><?php echo esc_html($faq['question']); ?></span>
                        <?php if ($layout === 'accordion') : ?>
                            <span class="prorank-faq-icon prorank-faq-icon-open" <?php echo $is_open ? 'style="display:none;"' : ''; ?>>
                                <?php Icons_Manager::render_icon($settings['icon_open'], ['aria-hidden' => 'true']); ?>
                            </span>
                            <span class="prorank-faq-icon prorank-faq-icon-close" <?php echo !$is_open ? 'style="display:none;"' : ''; ?>>
                                <?php Icons_Manager::render_icon($settings['icon_close'], ['aria-hidden' => 'true']); ?>
                            </span>
                        <?php endif; ?>
                    </<?php echo $layout === 'accordion' ? 'button' : 'h3'; ?>>
                    <div
                        class="prorank-faq-answer"
                        id="faq-answer-<?php echo esc_attr($widget_id . '-' . $index); ?>"
                        <?php if ($layout === 'accordion' && !$is_open) : ?>
                            style="display: none;"
                        <?php endif; ?>
                    >
                        <?php echo wp_kses_post($faq['answer']); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if ($layout === 'accordion') : ?>
            <script>
            (function() {
                const widget = document.querySelector('.elementor-element-<?php echo esc_js($widget_id); ?> .prorank-faq-widget');
                if (!widget) return;

                widget.querySelectorAll('.prorank-faq-question').forEach(function(question) {
                    question.addEventListener('click', function() {
                        const item = this.closest('.prorank-faq-item');
                        const answer = item.querySelector('.prorank-faq-answer');
                        const iconOpen = this.querySelector('.prorank-faq-icon-open');
                        const iconClose = this.querySelector('.prorank-faq-icon-close');
                        const isOpen = item.classList.contains('active');

                        if (isOpen) {
                            item.classList.remove('active');
                            answer.style.display = 'none';
                            this.setAttribute('aria-expanded', 'false');
                            if (iconOpen) iconOpen.style.display = '';
                            if (iconClose) iconClose.style.display = 'none';
                        } else {
                            item.classList.add('active');
                            answer.style.display = '';
                            this.setAttribute('aria-expanded', 'true');
                            if (iconOpen) iconOpen.style.display = 'none';
                            if (iconClose) iconClose.style.display = '';
                        }
                    });
                });
            })();
            </script>
        <?php endif; ?>

        <?php
        // Output FAQPage schema
        if ($enable_schema) {
            $this->output_faq_schema($faqs);
        }
    }

    /**
     * Output FAQPage structured data
     */
    private function output_faq_schema(array $faqs): void {
        $schema = [
            '@context'   => 'https://schema.org',
            '@type'      => 'FAQPage',
            'mainEntity' => [],
        ];

        foreach ($faqs as $faq) {
            if (empty($faq['question']) || empty($faq['answer'])) {
                continue;
            }

            $schema['mainEntity'][] = [
                '@type'          => 'Question',
                'name'           => wp_strip_all_tags($faq['question']),
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text'  => wp_strip_all_tags($faq['answer']),
                ],
            ];
        }

        if (empty($schema['mainEntity'])) {
            return;
        }

        printf(
            '<script type="application/ld+json">%s</script>',
            wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
        );
    }

    /**
     * Render widget output in editor
     */
    protected function content_template(): void {
        ?>
        <#
        var layout = settings.layout;
        var firstOpen = settings.first_open === 'yes';
        #>
        <div class="prorank-faq-widget prorank-faq-{{{ layout }}}">
            <# _.each( settings.faq_items, function( faq, index ) {
                var isOpen = ( layout === 'list' ) || ( firstOpen && index === 0 );
                var itemClass = isOpen ? 'prorank-faq-item active' : 'prorank-faq-item';
            #>
                <div class="{{{ itemClass }}}">
                    <# if ( layout === 'accordion' ) { #>
                        <button class="prorank-faq-question" type="button">
                            <span class="prorank-faq-question-text">{{{ faq.question }}}</span>
                            <span class="prorank-faq-icon prorank-faq-icon-open" <# if ( isOpen ) { #>style="display:none;"<# } #>>
                                <i class="fas fa-plus"></i>
                            </span>
                            <span class="prorank-faq-icon prorank-faq-icon-close" <# if ( ! isOpen ) { #>style="display:none;"<# } #>>
                                <i class="fas fa-minus"></i>
                            </span>
                        </button>
                    <# } else { #>
                        <h3 class="prorank-faq-question">
                            <span class="prorank-faq-question-text">{{{ faq.question }}}</span>
                        </h3>
                    <# } #>
                    <div class="prorank-faq-answer" <# if ( layout === 'accordion' && ! isOpen ) { #>style="display:none;"<# } #>>
                        {{{ faq.answer }}}
                    </div>
                </div>
            <# }); #>
        </div>
        <# if ( settings.enable_schema === 'yes' ) { #>
            <div class="prorank-schema-notice" style="margin-top: 10px; padding: 8px 12px; background: #e8f5e9; border-left: 3px solid #4caf50; font-size: 12px;">
                FAQPage schema will be added automatically
            </div>
        <# } #>
        <?php
    }
}
