<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;

class Sifency_Widget_Auto_Popup extends Widget_Base {

    public function get_name() {
        return 'sifency-widget-auto-popup';
    }

    public function get_title() {
        return esc_html__('Sifency Auto Popup', 'sifency-addons');
    }

    public function get_icon() {
        return 'eicon-banner';
    }

    public function get_categories() {
        return ['sifency-addons-widgets'];
    }

    public function get_script_depends() {
        return [ 'sifency-popup-script' ]; 
    }

    public function get_style_depends() {
        return [ 'sifency-popup-style' ]; 
    }

    protected function get_elementor_templates() {
        $templates = \Elementor\Plugin::$instance->templates_manager->get_source( 'local' )->get_items();
        $options = [ '0' => 'Select Template' ];
        if ( ! empty( $templates ) ) {
            foreach ( $templates as $template ) {
                $options[ $template['template_id'] ] = $template['title'] . ' (' . $template['type'] . ')';
            }
        }
        return $options;
    }

    protected function register_controls() {

        // --- Content Section ---
        $this->start_controls_section(
            'section_content',
            [ 'label' => esc_html__('Popup Content', 'sifency-addons') ]
        );

        $this->add_control(
            'content_source',
            [
                'label' => esc_html__('Content Source', 'sifency-addons'),
                'type' => Controls_Manager::SELECT,
                'default' => 'custom',
                'options' => [
                    'custom' => 'Custom Content',
                    'template' => 'Elementor Template',
                ],
            ]
        );

        $this->add_control(
            'template_id',
            [
                'label' => esc_html__('Choose Template', 'sifency-addons'),
                'type' => Controls_Manager::SELECT,
                'options' => $this->get_elementor_templates(),
                'default' => '0',
                'condition' => [ 'content_source' => 'template' ],
            ]
        );

        $this->add_control(
            'custom_content',
            [
                'label' => esc_html__('Custom Text/HTML', 'sifency-addons'),
                'type' => Controls_Manager::WYSIWYG,
                'default' => '<h2>Subscribe to our Newsletter</h2><p>Get the latest news and updates.</p>',
                'condition' => [ 'content_source' => 'custom' ],
            ]
        );

        $this->end_controls_section();

        // --- Settings Section ---
        $this->start_controls_section(
            'section_settings',
            [ 'label' => esc_html__('Popup Settings', 'sifency-addons') ]
        );

        $this->add_control(
            'trigger_delay',
            [
                'label' => esc_html__('Open Delay (Seconds)', 'sifency-addons'),
                'type' => Controls_Manager::NUMBER,
                'min' => 0,
                'max' => 60,
                'step' => 0.5,
                'default' => 1,
                'description' => 'How long to wait after page load before showing the popup.',
            ]
        );

        $this->add_control(
            'show_once',
            [
                'label' => esc_html__('Show Once Per Session', 'sifency-addons'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => 'Yes',
                'label_off' => 'No',
                'return_value' => 'yes',
                'default' => 'no',
                'description' => 'If Yes, the popup will not show again until the browser is closed and reopened (uses Session Storage).',
            ]
        );

        $this->add_control(
            'prevent_scroll',
            [
                'label' => esc_html__('Prevent Page Scroll', 'sifency-addons'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'description' => 'Stop background scrolling when popup is open.',
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'section_style_popup',
            [
                'label' => esc_html__('Popup Container', 'sifency-addons'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'popup_width',
            [
                'label' => esc_html__('Width', 'sifency-addons'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range' => [ 'px' => [ 'min' => 200, 'max' => 1000 ] ],
                'default' => [ 'unit' => 'px', 'size' => 600 ],
                'selectors' => [ '{{WRAPPER}} .sifency-auto-popup-container' => 'width: {{SIZE}}{{UNIT}};' ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'popup_background',
                'types' => [ 'classic', 'gradient' ],
                'selector' => '{{WRAPPER}} .sifency-auto-popup-container',
            ]
        );

        $this->add_responsive_control('popup_padding', ['label' => 'Padding', 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px'], 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-content' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'popup_border', 'selector' => '{{WRAPPER}} .sifency-auto-popup-container']);
        $this->add_responsive_control('popup_radius', ['label' => 'Border Radius', 'type' => Controls_Manager::DIMENSIONS, 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-container' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [ 'name' => 'popup_shadow', 'selector' => '{{WRAPPER}} .sifency-auto-popup-container' ]);

        $this->end_controls_section();

        $this->start_controls_section(
            'section_style_close',
            [ 'label' => esc_html__('Close Button', 'sifency-addons'), 'tab' => Controls_Manager::TAB_STYLE ]
        );

        $this->add_control('close_color', ['label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-close' => 'color: {{VALUE}};']]);
        $this->add_control('close_bg_color', ['label' => 'Background Color', 'type' => Controls_Manager::COLOR, 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-close' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('close_size', ['label' => 'Size', 'type' => Controls_Manager::SLIDER, 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-close' => 'font-size: {{SIZE}}px;']]);

        $this->end_controls_section();

        $this->start_controls_section(
            'section_style_overlay',
            [ 'label' => esc_html__('Overlay', 'sifency-addons'), 'tab' => Controls_Manager::TAB_STYLE ]
        );
        $this->add_control('overlay_color', ['label' => 'Color', 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.7)', 'selectors' => ['{{WRAPPER}} .sifency-auto-popup-overlay' => 'background-color: {{VALUE}};']]);
        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        
        $content_html = '';
        if ( 'template' === $settings['content_source'] && ! empty( $settings['template_id'] ) ) {
            $content_html = \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $settings['template_id'] );
        } else {
            $content_html = $settings['custom_content'];
        }

        $this->add_render_attribute( 'wrapper', [
            'class' => 'sifency-auto-popup-wrapper',
            'data-delay' => $settings['trigger_delay'] * 1000, 
            'data-show-once' => $settings['show_once'],
            'data-prevent-scroll' => $settings['prevent_scroll'],
            'data-widget-id' => $this->get_id(), 
        ]);

        if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
            echo '<div style="background:#eee; padding:20px; text-align:center; border:1px dashed #999;">';
            echo '<i class="eicon-banner" style="font-size:30px; display:block; margin-bottom:10px;"></i>';
            echo '<small>(To edit the content, switch the "Content Source" or "Choose Template")</small>';
            echo '</div>';
        }
        ?>

        <div <?php echo wp_kses ( $this->get_render_attribute_string('wrapper'), [] ); ?> style="display:none;">
            <div class="sifency-auto-popup-overlay"></div>
            <div class="sifency-auto-popup-container">
                <button class="sifency-auto-popup-close"><i class="eicon-close"></i></button>
                <div class="sifency-auto-popup-content">
                    <?php echo wp_kses_post ( $content_html ); ?>
                </div>
            </div>
        </div>
        <?php
    }
}