<?php
namespace Unlockafe_addons\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;

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

class Dynamic_Chart extends Widget_Base {

     public function get_name() {
        return 'unlockafe-dynamic-chart';
    }

    public function get_title() {
        return esc_html__('Dynamic Chart', 'unlock-addons-for-elementor');
    }

    public function get_icon() {
        return 'eicon-skill-bar ulicon';
    }

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

    public function get_keywords() {
        return ['unlock', 'chart', 'graph', 'dynamic'];
    }

    public function get_script_depends() {
        return ['unlockafe-dynamic-chart'];
    }

    public function get_style_depends() {
        return ['unlockafe-dynamic-chart'];
    }

        protected function register_controls() {
        $this->start_controls_section(
            'section_chart_content',
            [
                'label' => esc_html__('Chart Content', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'chart_type',
            [
                'label' => esc_html__('Chart Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'bar',
                'options' => [
                    'bar' => esc_html__('Bar', 'unlock-addons-for-elementor'),
                    'line' => esc_html__('Line', 'unlock-addons-for-elementor'),
                    'pie' => esc_html__('Pie', 'unlock-addons-for-elementor'),
                    'doughnut' => esc_html__('Doughnut', 'unlock-addons-for-elementor'),
                    'radar' => esc_html__('Radar', 'unlock-addons-for-elementor'),
                    'polarArea' => esc_html__('Polar Area', 'unlock-addons-for-elementor'),
                ],
            ]
        );

        $this->add_control(
            'chart_labels',
            [
                'label' => esc_html__('Labels', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => 'January, February, March, April, May, June, July',
                'description' => esc_html__('Enter comma-separated labels for the chart.', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'dataset_label',
            [
                'label' => esc_html__('Dataset Label', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('My First Dataset', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'dataset_data',
            [
                'label' => esc_html__('Data', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => '65, 59, 80, 81, 56, 55, 40',
                'description' => esc_html__('Enter comma-separated numerical data.', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'color_palette',
            [
                'label' => esc_html__('Color Palette', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'vibrant',
                'options' => [
                    'custom' => esc_html__('Custom', 'unlock-addons-for-elementor'),
                    'vibrant' => esc_html__('Vibrant', 'unlock-addons-for-elementor'),
                    'cool' => esc_html__('Cool', 'unlock-addons-for-elementor'),
                    'warm' => esc_html__('Warm', 'unlock-addons-for-elementor'),
                ],
            ]
        );

        $repeater->add_control(
            'dataset_bg_color',
            [
                'label' => esc_html__('Background Color(s)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => 'rgba(75, 192, 192, 0.2)',
                'description' => esc_html__('Enter one color or a comma-separated list of colors (e.g., for pie/doughnut charts).', 'unlock-addons-for-elementor'),
                'condition' => [
                    'color_palette' => 'custom',
                ],
            ]
        );

        $repeater->add_control(
            'dataset_border_color',
            [
                'label' => esc_html__('Border Color(s)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => 'rgba(75, 192, 192, 1)',
                'description' => esc_html__('Enter one color or a comma-separated list of colors.', 'unlock-addons-for-elementor'),
                'condition' => [
                    'color_palette' => 'custom',
                ],
            ]
        );

        $this->add_control(
            'datasets',
            [
                'label' => esc_html__('Datasets', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'dataset_label' => esc_html__('Sample Dataset', 'unlock-addons-for-elementor'),
                        'dataset_data' => '65, 59, 80, 81, 56, 55, 40',
                        'dataset_bg_color' => 'rgba(75, 192, 192, 0.2)',
                        'dataset_border_color' => 'rgba(75, 192, 192, 1)',
                    ],
                ],
                'title_field' => '{{{ dataset_label }}}',
            ]
        );

        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        $chart_id = 'unlock-chart-' . $this->get_id();
        
        // Check if we're in Elementor editor or preview mode
        $is_editor_mode = \Elementor\Plugin::$instance->editor->is_edit_mode();
        $is_preview_mode = \Elementor\Plugin::$instance->preview->is_preview_mode();
        
        // Ensure scripts are loaded on the front end and in editor/preview mode
        if (!is_admin() || $is_editor_mode || $is_preview_mode) {
            // Enqueue Chart.js from CDN
            if (!wp_script_is('chart-js', 'enqueued')) {
                wp_enqueue_script(
                    'chart-js',
                    'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js',
                    [],
                    '3.9.1',
                    true
                );
            }
            
            // Enqueue dynamic chart script
            wp_enqueue_script('unlockafe-dynamic-chart');
            
            // Add inline script for editor/preview mode initialization
            if ($is_editor_mode || $is_preview_mode) {
                wp_add_inline_script('unlockafe-dynamic-chart', "
                    (function() {
                        function initEditorChart() {
                            if (typeof Chart === 'undefined' || typeof jQuery === 'undefined') {
                                setTimeout(initEditorChart, 100);
                                return;
                            }
                            
                            var $ = jQuery;
                            $('.unlock-chart-container').each(function() {
                                var $container = $(this);
                                if ($container.data('initialized')) {
                                    return;
                                }
                                
                                var settings = $container.data('settings');
                                if (!settings) {
                                    return;
                                }
                                
                                var canvas = $container.find('canvas')[0];
                                if (!canvas) {
                                    return;
                                }
                                
                                var chartId = canvas.id || '" . esc_js($chart_id) . "';
                                canvas.id = chartId;
                                
                                // Destroy existing chart if any
                                if (window.unlockChartRegistry && window.unlockChartRegistry[chartId]) {
                                    try {
                                        window.unlockChartRegistry[chartId].destroy();
                                    } catch(e) {}
                                    delete window.unlockChartRegistry[chartId];
                                }
                                
                                // Create new chart
                                try {
                                    window.unlockChartRegistry = window.unlockChartRegistry || {};
                                    window.unlockChartRegistry[chartId] = new Chart(canvas, {
                                        type: settings.type,
                                        data: {
                                            labels: settings.labels,
                                            datasets: settings.datasets
                                        },
                                        options: settings.options || {}
                                    });
                                    $container.data('initialized', true);
                                } catch(e) {
                                    console.error('Error creating chart:', e);
                                }
                            });
                        }
                        
                        // Wait for DOM and scripts to be ready
                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', function() {
                                setTimeout(initEditorChart, 200);
                            });
                        } else {
                            setTimeout(initEditorChart, 200);
                        }
                        
                        // Also try after Elementor frontend is ready
                        if (typeof elementorFrontend !== 'undefined') {
                            $(window).on('elementor/frontend/init', function() {
                                setTimeout(initEditorChart, 300);
                            });
                        }
                    })();
                ");
            }
        }

        $palettes = [
            'vibrant' => [
                'background' => ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)'],
                'border' => ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)'],
            ],
            'cool' => [
                'background' => ['rgba(6, 146, 208, 0.2)', 'rgba(115, 208, 227, 0.2)', 'rgba(115, 166, 227, 0.2)', 'rgba(6, 79, 208, 0.2)', 'rgba(19, 35, 139, 0.2)', 'rgba(115, 227, 203, 0.2)'],
                'border' => ['rgba(6, 146, 208, 1)', 'rgba(115, 208, 227, 1)', 'rgba(115, 166, 227, 1)', 'rgba(6, 79, 208, 1)', 'rgba(19, 35, 139, 1)', 'rgba(115, 227, 203, 1)'],
            ],
            'warm' => [
                'background' => ['rgba(255, 107, 107, 0.2)', 'rgba(255, 169, 107, 0.2)', 'rgba(255, 225, 107, 0.2)', 'rgba(227, 126, 95, 0.2)', 'rgba(195, 87, 61, 0.2)', 'rgba(227, 168, 95, 0.2)'],
                'border' => ['rgba(255, 107, 107, 1)', 'rgba(255, 169, 107, 1)', 'rgba(255, 225, 107, 1)', 'rgba(227, 126, 95, 1)', 'rgba(195, 87, 61, 1)', 'rgba(227, 168, 95, 1)'],
            ],
        ];

        // Process datasets
        $datasets = [];
        foreach ($settings['datasets'] as $dataset) {
            $bg_colors = [];
            $border_colors = [];

            if ($dataset['color_palette'] === 'custom') {
                $bg_colors = array_map('trim', explode(',', $dataset['dataset_bg_color']));
                $border_colors = array_map('trim', explode(',', $dataset['dataset_border_color']));
            } else if (isset($palettes[$dataset['color_palette']])) {
                $palette = $palettes[$dataset['color_palette']];
                $bg_colors = $palette['background'];
                $border_colors = $palette['border'];
            }

            $datasets[] = [
                'label' => $dataset['dataset_label'],
                'data' => array_map('intval', explode(',', $dataset['dataset_data'])),
                'backgroundColor' => count($bg_colors) > 1 ? $bg_colors : ($bg_colors[0] ?? 'rgba(75, 192, 192, 0.2)'),
                'borderColor' => count($border_colors) > 1 ? $border_colors : ($border_colors[0] ?? 'rgba(75, 192, 192, 1)'),
                'borderWidth' => 1,
            ];
        }
        
        // Create chart settings
        $chart_settings = [
            'type' => $settings['chart_type'],
            'labels' => array_map('trim', explode(',', $settings['chart_labels'])),
            'datasets' => $datasets,
            'options' => $this->get_chart_options($settings),
        ];

        $this->add_render_attribute(
            'chart_container',
            [
                'class' => 'unlock-chart-container',
                'data-settings' => wp_json_encode($chart_settings),
            ]
        );

        ?>
        <div <?php echo $this->get_render_attribute_string('chart_container'); ?>>
            <canvas id="<?php echo esc_attr($chart_id); ?>"></canvas>
        </div>
        <?php
        
        // Add inline script directly after widget HTML for immediate initialization in editor
        if ($is_editor_mode || $is_preview_mode) {
            $chart_settings_json = wp_json_encode($chart_settings);
            ?>
            <script type="text/javascript">
            (function() {
                var chartId = '<?php echo esc_js($chart_id); ?>';
                var chartSettings = <?php echo $chart_settings_json; ?>;
                var initAttempts = 0;
                var maxAttempts = 30; // Try for 3 seconds (30 * 100ms)
                
                // Function to load Chart.js if not available
                function loadChartJS() {
                    if (typeof Chart !== 'undefined') {
                        return Promise.resolve();
                    }
                    
                    return new Promise(function(resolve, reject) {
                        // Check if script is already being loaded
                        if (document.querySelector('script[src*="chart.js"]')) {
                            var checkInterval = setInterval(function() {
                                if (typeof Chart !== 'undefined') {
                                    clearInterval(checkInterval);
                                    resolve();
                                }
                            }, 50);
                            setTimeout(function() {
                                clearInterval(checkInterval);
                                reject(new Error('Chart.js load timeout'));
                            }, 5000);
                            return;
                        }
                        
                        // Load Chart.js
                        var script = document.createElement('script');
                        script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
                        script.onload = function() {
                            resolve();
                        };
                        script.onerror = function() {
                            reject(new Error('Failed to load Chart.js'));
                        };
                        document.head.appendChild(script);
                    });
                }
                
                function initThisChart() {
                    initAttempts++;
                    
                    var canvas = document.getElementById(chartId);
                    if (!canvas) {
                        if (initAttempts < maxAttempts) {
                            setTimeout(initThisChart, 100);
                        } else {
                            console.error('Dynamic Chart: Canvas not found after', maxAttempts, 'attempts');
                        }
                        return;
                    }
                    
                    if (typeof Chart === 'undefined') {
                        if (initAttempts < maxAttempts) {
                            loadChartJS().then(function() {
                                setTimeout(initThisChart, 100);
                            }).catch(function(err) {
                                console.error('Dynamic Chart: Failed to load Chart.js', err);
                            });
                        } else {
                            console.error('Dynamic Chart: Chart.js not available after', maxAttempts, 'attempts');
                        }
                        return;
                    }
                    
                    try {
                        // Destroy existing chart if any
                        if (window.unlockChartRegistry && window.unlockChartRegistry[chartId]) {
                            try {
                                window.unlockChartRegistry[chartId].destroy();
                            } catch(e) {
                                console.log('Error destroying existing chart:', e);
                            }
                            delete window.unlockChartRegistry[chartId];
                        }
                        
                        // Create chart registry if it doesn't exist
                        window.unlockChartRegistry = window.unlockChartRegistry || {};
                        
                        // Create new chart
                        window.unlockChartRegistry[chartId] = new Chart(canvas, {
                            type: chartSettings.type,
                            data: {
                                labels: chartSettings.labels,
                                datasets: chartSettings.datasets
                            },
                            options: chartSettings.options || {}
                        });
                        
                        console.log('Dynamic Chart: Successfully initialized chart', chartId);
                    } catch(e) {
                        console.error('Dynamic Chart: Error creating chart', chartId, e);
                    }
                }
                
                // Start initialization
                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', function() {
                        setTimeout(initThisChart, 100);
                    });
                } else {
                    setTimeout(initThisChart, 100);
                }
            })();
            </script>
            <?php
        }
    }

    private function get_chart_options($settings) {
        $options = [];
        
        // Set responsive options for all chart types
        $options['responsive'] = true;
        $options['maintainAspectRatio'] = true;
        
        // Add specific options based on chart type
        switch ($settings['chart_type']) {
            case 'bar':
                $options['scales'] = [
                    'y' => [
                        'beginAtZero' => true
                    ]
                ];
                break;
                
            case 'line':
                $options['scales'] = [
                    'y' => [
                        'beginAtZero' => true
                    ]
                ];
                $options['elements'] = [
                    'line' => [
                        'tension' => 0.4
                    ]
                ];
                break;
                
            case 'pie':
            case 'doughnut':
                $options['plugins'] = [
                    'legend' => [
                        'position' => 'top',
                    ],
                    'tooltip' => [
                        'enabled' => true
                    ]
                ];
                break;
                
            case 'radar':
                $options['elements'] = [
                    'line' => [
                        'borderWidth' => 3
                    ]
                ];
                break;
                
            case 'polarArea':
                $options['plugins'] = [
                    'legend' => [
                        'position' => 'right',
                    ]
                ];
                break;
        }
        return $options;
    }

}