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

class PollBolt_Elementor_Widget extends \Elementor\Widget_Base {
    public function get_name() {
        return 'pollbolt-ai-forms-polls-quizzes';
    }

    public function get_title() {
        return 'PollBolt';
    }

    public function get_icon() {
        return 'pollbolt-icon';
    }

    /**
     * Get custom help URL for the widget
     */
    public function get_custom_help_url() {
        return '';
    }

    /**
     * Add custom styles for the widget icon
     */
    public function __construct($data = [], $args = null) {
        parent::__construct($data, $args);
        
        // Enqueue Elementor widget styles
        wp_enqueue_style('pollbolt-elementor-widget', plugins_url('css/elementor-widget.css', __FILE__), array(), '1.0.0');
        
        // Add script for hiding scrollbars
        add_action('wp_head', [$this, 'add_scrollbar_hiding_styles']);
        add_action('wp_footer', [$this, 'add_resizing_script']);
    }
    
    /**
     * Add styles for hiding scrollbars in head
     */
    public function add_scrollbar_hiding_styles() {
        wp_enqueue_style('pollbolt-scrollbar-styles', plugins_url('css/scrollbar-hide.css', __FILE__), array(), '1.0.0');
    }
    
    /**
     * Add script for automatic resizing in footer
     */
    public function add_resizing_script() {
        wp_enqueue_script('pollbolt-elementor-widget', plugins_url('js/elementor-widget.js', __FILE__), array(), '1.0.0', true);
    }

    public function get_categories() {
        return ['general'];
    }

    protected function register_controls() {
        $this->start_controls_section(
            'content_section',
            [
                'label' => 'Settings',
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        // Get list of all shortcodes from the database
        global $wpdb;
        $table_name = $wpdb->prefix . 'pollbolt_surveys';
        // Direct database query is necessary to get data from custom database table
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $surveys = $wpdb->get_results("SELECT id, name, shortcode, url FROM " . esc_sql($table_name) . " ORDER BY name ASC");
        
        // Check if there are any surveys
        $has_surveys = !empty($surveys);
        
        // Add button to go to PollBolt settings
        $admin_url = admin_url('admin.php?page=pollbolt-settings');
        
        // If no surveys, show warning and button
        if (!$has_surveys) {
            $this->add_control(
                'no_surveys_notice',
                [
                    'type' => \Elementor\Controls_Manager::RAW_HTML,
                    'raw' => '<div style="background-color: #FFFD63; border: 1px solid #FFD700; color: #333; padding: 15px; border-radius: 3px; margin-bottom: 15px;">
                        <p style="margin: 0 0 10px 0;"><strong>No PollBolt forms found!</strong></p>
                        <p style="margin: 0 0 10px 0;">You need to create a PollBolt form first from the WordPress admin panel.</p>
                        <a href="' . esc_url($admin_url) . '" target="_blank" class="elementor-button" style="display: inline-block; text-decoration: none; background-color: #333; color: #FFFD63; padding: 10px 15px; border-radius: 3px; font-weight: bold;">
                            <i class="eicon-plus" style="margin-right: 5px;"></i> Create New Form
                        </a>
                    </div>',
                ]
            );
        }
        
        // Show form management button only if there is at least one survey
        if ($has_surveys) {
            $this->add_control(
                'go_to_settings_button',
                [
                    'type' => \Elementor\Controls_Manager::RAW_HTML,
                    'raw' => '<div style="text-align: center; margin-bottom: 15px;">
                        <a href="' . esc_url($admin_url) . '" target="_blank" style="display: inline-block; text-decoration: none; color: #333; padding: 8px 12px; border: 1px solid #FFD700; border-radius: 3px; background: #FFFD63; font-size: 12px;">
                            <i class="eicon-cog" style="margin-right: 5px;"></i> Manage PollBolt Forms
                        </a>
                    </div>',
                    'separator' => 'before',
                ]
            );
        }
        
        // Create options array for dropdown
        $shortcode_options = ['' => 'Select a form...'];
        if ($has_surveys) {
            foreach ($surveys as $survey) {
                $shortcode_options[$survey->shortcode] = $survey->name . ' - [' . $survey->shortcode . ']';
            }
        }
        
        // Form selection option
        $this->add_control(
            'pollbolt_shortcode',
            [
                'label' => 'Select Form',
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => $shortcode_options,
                'default' => '',
                'description' => 'Select a form from your saved forms',
            ]
        );

        // Size controls
        $this->add_control(
            'height_heading',
            [
                'label' => 'Size Settings',
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        // Custom height option
        $this->add_control(
            'custom_height_enabled',
            [
                'label' => 'Custom Height',
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => 'Yes',
                'label_off' => 'No',
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_responsive_control(
            'iframe_height',
            [
                'label' => 'Height',
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', 'vh', '%'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 1500,
                        'step' => 10,
                    ],
                    'vh' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                    '%' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 500,
                ],
                'selectors' => [
                    '{{WRAPPER}} .pollbolt-iframe-container' => 'height: {{SIZE}}{{UNIT}} !important;',
                    '{{WRAPPER}} .pollbolt-iframe' => 'height: 100% !important;',
                ],
                'condition' => [
                    'custom_height_enabled' => 'yes',
                ],
            ]
        );

        // Custom width option
        $this->add_control(
            'custom_width_enabled',
            [
                'label' => 'Custom Width',
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => 'Yes',
                'label_off' => 'No',
                'return_value' => 'yes',
                'default' => '',
                'separator' => 'before',
            ]
        );

        $this->add_responsive_control(
            'iframe_width',
            [
                'label' => 'Width',
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', 'vw', '%'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 1500,
                        'step' => 10,
                    ],
                    'vw' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                    '%' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => '%',
                    'size' => 100,
                ],
                'selectors' => [
                    '{{WRAPPER}} .pollbolt-iframe-container' => 'width: {{SIZE}}{{UNIT}} !important; max-width: {{SIZE}}{{UNIT}} !important;',
                ],
                'condition' => [
                    'custom_width_enabled' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        
        // Check if a survey is selected
        if (empty($settings['pollbolt_shortcode'])) {
            // If no survey selected, show message
            echo '<div style="border: 1px dashed #ddd; padding: 20px; text-align: center; background: #f7f7f7;">';
            echo '<p>' . esc_html__('Please select a PollBolt form from the widget settings', 'pollbolt-ai-forms-polls-quizzes') . '</p>';
            echo '</div>';
            return;
        }
        
        // Check if the shortcode is an Elementor system shortcode
        if (strpos($settings['pollbolt_shortcode'], 'wp_ajax_elementor') !== false) {
            echo '<p>' . esc_html__('Invalid shortcode detected', 'pollbolt-ai-forms-polls-quizzes') . '</p>';
            return;
        }
        
        // Get survey URL from database by shortcode
        global $wpdb;
        $table_name = $wpdb->prefix . 'pollbolt_surveys';
        $shortcode = $settings['pollbolt_shortcode'];
        
        // Direct database query is necessary to get data from custom database table
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $survey = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM " . esc_sql($table_name) . " WHERE shortcode = %s",
            $shortcode
        ));
        
        if (!$survey) {
            echo '<div style="color: red; padding: 10px; border: 1px solid #f0f0f0;">';
            echo esc_html__('Survey not found. Please select another survey.', 'pollbolt-ai-forms-polls-quizzes');
            echo '</div>';
            return;
        }
        
        // Get survey URL
        $url = $survey->url;
        
        // Add parameters for better display
        $url = add_query_arg([
            'embedded' => 'true',
            'hideScroll' => 'true',
            'autoresize' => 'true',
            'disableScrolling' => 'true',
            'hideScrollbars' => 'true'
        ], $url);
        
        // Generate unique ID for iframe
        $iframe_id = 'pollbolt-iframe-' . uniqid();
        
        // Set container style based on settings
        $container_style = '';
        
        // If custom height is not enabled, add inline style height:100%
        if (empty($settings['custom_height_enabled']) || $settings['custom_height_enabled'] !== 'yes') {
            $container_style .= 'height:100%;';
        }
        
        // If custom width is not enabled, add inline style width:100%
        if (empty($settings['custom_width_enabled']) || $settings['custom_width_enabled'] !== 'yes') {
            $container_style .= 'width:100%;';
        }
        
        // Output iframe in container with settings
        echo '<div class="pollbolt-iframe-container" style="' . esc_attr($container_style) . '">';
        echo '<iframe id="' . esc_attr($iframe_id) . '" class="pollbolt-iframe" src="' . esc_url($url) . '" width="100%" height="100%" scrolling="no" frameborder="0" allowtransparency="true" style="height:100%;"></iframe>';
        echo '</div>';
        
        // Add script for automatic iframe resizing
        $iframe_script = '
        document.addEventListener("DOMContentLoaded", function() {
            var iframe = document.getElementById("' . esc_js($iframe_id) . '");
            if (!iframe) return;
            
            // Process messages from iframe
            window.addEventListener("message", function(event) {
                ' . (empty($settings['custom_height_enabled']) || $settings['custom_height_enabled'] !== 'yes' ? '
                if (typeof event.data === "object" && event.data.type === "pollbolt-height") {
                    // Got height from PollBolt
                    var height = parseInt(event.data.height) + 100; // Add padding
                    iframe.style.height = height + "px";
                }
                ' : '') . '
                
                if (typeof event.data === "object" && event.data.type === "pollbolt-loaded") {
                    // PollBolt loaded, send settings
                    iframe.contentWindow.postMessage({
                        type: "pollbolt-parent-ready",
                        disableScrolling: true,
                        hideScrollbars: true
                    }, "*");
                }
            });
            
            // Periodically check size
            function checkSize() {
                // Send height request
                iframe.contentWindow.postMessage({
                    type: "pollbolt-get-height"
                }, "*");
                
                setTimeout(checkSize, 2000);
            }
            
            // Start check after loading
            iframe.onload = function() {
                // Immediate check
                setTimeout(checkSize, 500);
                
                // Add CSS to hide scrollbars
                try {
                    var iframeDoc = iframe.contentWindow.document;
                    var style = iframeDoc.createElement("style");
                    style.textContent = `
                        html, body { 
                            overflow: hidden !important; 
                            scrollbar-width: none !important;
                            -ms-overflow-style: none !important;
                        }
                        ::-webkit-scrollbar { 
                            display: none !important; 
                            width: 0 !important; 
                            height: 0 !important; 
                        }
                    `;
                    iframeDoc.head.appendChild(style);
                } catch(e) {
                    // Expected cross-origin errors, ignore
                }
            };
            
            // Start size check
            checkSize();
        });
    ';
        
        // Enqueue the iframe-specific script as inline
        wp_register_script('pollbolt-iframe-' . $iframe_id, false, array(), '1.0.0', true);
        wp_enqueue_script('pollbolt-iframe-' . $iframe_id);
        wp_add_inline_script('pollbolt-iframe-' . $iframe_id, $iframe_script);
    }
} 