<?php
/**
 * TableCrafter Elementor Widget
 * 
 * Native Elementor widget providing seamless integration with live preview,
 * visual controls, and professional workflow for the 12+ million Elementor users.
 * 
 * @package TableCrafter
 * @since 3.2.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Scheme_Typography;
use Elementor\Scheme_Color;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

/**
 * TableCrafter Elementor Widget Class
 * 
 * Provides native Elementor integration with live preview and visual controls
 */
class TC_Elementor_Widget extends Widget_Base
{
    /**
     * Widget name
     */
    public function get_name()
    {
        return 'tablecrafter-data-table';
    }

    /**
     * Widget title
     */
    public function get_title()
    {
        return esc_html__('TableCrafter Data Table', 'tablecrafter-wp-data-tables');
    }

    /**
     * Widget icon
     */
    public function get_icon()
    {
        return 'eicon-table';
    }

    /**
     * Widget categories
     */
    public function get_categories()
    {
        return ['general', 'tablecrafter'];
    }

    /**
     * Widget keywords
     */
    public function get_keywords()
    {
        return ['table', 'data', 'json', 'api', 'csv', 'google sheets', 'tablecrafter'];
    }

    /**
     * Widget dependencies
     */
    public function get_script_depends()
    {
        return ['tablecrafter-lib', 'tablecrafter-frontend'];
    }

    /**
     * Widget styles
     */
    public function get_style_depends()
    {
        return ['tablecrafter-style'];
    }

    /**
     * Register widget controls
     */
    protected function register_controls()
    {
        $this->register_data_source_controls();
        $this->register_display_controls();
        $this->register_advanced_controls();
        $this->register_style_controls();
    }

    /**
     * Data Source Controls Section
     */
    protected function register_data_source_controls()
    {
        $this->start_controls_section(
            'section_data_source',
            [
                'label' => esc_html__('Data Source', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'source_type',
            [
                'label' => esc_html__('Source Type', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SELECT,
                'default' => 'url',
                'options' => [
                    'url' => esc_html__('API URL / JSON File', 'tablecrafter-wp-data-tables'),
                    'google_sheets' => esc_html__('Google Sheets', 'tablecrafter-wp-data-tables'),
                    'csv_file' => esc_html__('CSV File', 'tablecrafter-wp-data-tables'),
                ],
            ]
        );

        $this->add_control(
            'data_source',
            [
                'label' => esc_html__('Data Source URL', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::URL,
                'placeholder' => 'https://api.example.com/data.json',
                'description' => esc_html__('Enter the URL of your JSON API, CSV file, or Google Sheets public URL.', 'tablecrafter-wp-data-tables'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'google_sheets_help',
            [
                'type' => Controls_Manager::RAW_HTML,
                'raw' => '<div style="background: #e3f2fd; padding: 10px; border-radius: 4px; border-left: 4px solid #2196f3; margin: 10px 0;">
                    <strong>Google Sheets Setup:</strong><br>
                    1. Make your sheet public<br>
                    2. Use format: <code>https://docs.google.com/spreadsheets/d/[ID]/gviz/tq?tqx=out:csv</code><br>
                    <a href="https://tablecrafter.com/docs/google-sheets" target="_blank">View detailed guide →</a>
                </div>',
                'condition' => [
                    'source_type' => 'google_sheets',
                ],
            ]
        );

        $this->add_control(
            'root_path',
            [
                'label' => esc_html__('JSON Root Path', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => 'data.results',
                'description' => esc_html__('If your data is nested in JSON, specify the path (e.g., "data.results").', 'tablecrafter-wp-data-tables'),
                'condition' => [
                    'source_type' => ['url'],
                ],
            ]
        );

        $this->add_control(
            'include_columns',
            [
                'label' => esc_html__('Include Columns', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => 'name,email,date',
                'description' => esc_html__('Comma-separated list of columns to include. Leave empty to show all.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'exclude_columns',
            [
                'label' => esc_html__('Exclude Columns', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => 'id,internal_notes',
                'description' => esc_html__('Comma-separated list of columns to exclude.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Display Controls Section
     */
    protected function register_display_controls()
    {
        $this->start_controls_section(
            'section_display',
            [
                'label' => esc_html__('Display Options', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'enable_search',
            [
                'label' => esc_html__('Enable Global Search', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'description' => esc_html__('Add a search box above the table for filtering data.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'enable_filters',
            [
                'label' => esc_html__('Enable Advanced Filters', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'description' => esc_html__('Automatic column-based filters (dropdowns, date ranges, etc.).', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'enable_export',
            [
                'label' => esc_html__('Enable Data Export', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SWITCHER,
                'default' => '',
                'description' => esc_html__('Allow users to export table data as CSV, Excel, or PDF.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'per_page',
            [
                'label' => esc_html__('Rows Per Page', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::NUMBER,
                'default' => 25,
                'min' => 1,
                'max' => 1000,
                'description' => esc_html__('Number of rows to show per page. Set to 0 to disable pagination.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'sort_column',
            [
                'label' => esc_html__('Default Sort Column', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => 'name',
                'description' => esc_html__('Column name to sort by initially.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'sort_order',
            [
                'label' => esc_html__('Sort Order', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SELECT,
                'default' => 'asc',
                'options' => [
                    'asc' => esc_html__('Ascending (A-Z, 1-9)', 'tablecrafter-wp-data-tables'),
                    'desc' => esc_html__('Descending (Z-A, 9-1)', 'tablecrafter-wp-data-tables'),
                ],
                'condition' => [
                    'sort_column!' => '',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Advanced Controls Section
     */
    protected function register_advanced_controls()
    {
        $this->start_controls_section(
            'section_advanced',
            [
                'label' => esc_html__('Advanced Features', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'auto_refresh',
            [
                'label' => esc_html__('Auto-Refresh Data', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::SWITCHER,
                'default' => '',
                'description' => esc_html__('Automatically refresh data from the source at specified intervals.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'refresh_interval',
            [
                'label' => esc_html__('Refresh Interval (seconds)', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::NUMBER,
                'default' => 300,
                'min' => 30,
                'max' => 86400,
                'description' => esc_html__('How often to refresh data (30 seconds to 24 hours).', 'tablecrafter-wp-data-tables'),
                'condition' => [
                    'auto_refresh' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'cache_duration',
            [
                'label' => esc_html__('Cache Duration (minutes)', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::NUMBER,
                'default' => 15,
                'min' => 0,
                'max' => 1440,
                'description' => esc_html__('How long to cache data for performance. Set to 0 to disable caching.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'loading_message',
            [
                'label' => esc_html__('Loading Message', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'default' => 'Loading data...',
                'description' => esc_html__('Message shown while data is being fetched.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->add_control(
            'error_message',
            [
                'label' => esc_html__('Error Message', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::TEXT,
                'default' => 'Unable to load data. Please try again.',
                'description' => esc_html__('Message shown when data loading fails.', 'tablecrafter-wp-data-tables'),
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Style Controls Section
     */
    protected function register_style_controls()
    {
        // Table Styling
        $this->start_controls_section(
            'section_table_style',
            [
                'label' => esc_html__('Table Styling', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'table_typography',
                'selector' => '{{WRAPPER}} .tc-table',
            ]
        );

        $this->add_control(
            'table_background',
            [
                'label' => esc_html__('Background Color', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .tc-table-container' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'table_border',
                'selector' => '{{WRAPPER}} .tc-table-container',
            ]
        );

        $this->add_control(
            'table_border_radius',
            [
                'label' => esc_html__('Border Radius', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .tc-table-container' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'table_shadow',
                'selector' => '{{WRAPPER}} .tc-table-container',
            ]
        );

        $this->end_controls_section();

        // Header Styling
        $this->start_controls_section(
            'section_header_style',
            [
                'label' => esc_html__('Header Styling', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'header_typography',
                'selector' => '{{WRAPPER}} .tc-table th',
            ]
        );

        $this->add_control(
            'header_background',
            [
                'label' => esc_html__('Background Color', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#f8f9fa',
                'selectors' => [
                    '{{WRAPPER}} .tc-table th' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'header_color',
            [
                'label' => esc_html__('Text Color', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#495057',
                'selectors' => [
                    '{{WRAPPER}} .tc-table th' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'header_padding',
            [
                'label' => esc_html__('Padding', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em'],
                'default' => [
                    'top' => '12',
                    'right' => '16',
                    'bottom' => '12',
                    'left' => '16',
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .tc-table th' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Rows Styling
        $this->start_controls_section(
            'section_rows_style',
            [
                'label' => esc_html__('Rows Styling', 'tablecrafter-wp-data-tables'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'row_background',
            [
                'label' => esc_html__('Row Background', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .tc-table td' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'row_hover_background',
            [
                'label' => esc_html__('Row Hover Background', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#f8f9fa',
                'selectors' => [
                    '{{WRAPPER}} .tc-table tr:hover td' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'row_color',
            [
                'label' => esc_html__('Text Color', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .tc-table td' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'row_padding',
            [
                'label' => esc_html__('Cell Padding', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em'],
                'default' => [
                    'top' => '12',
                    'right' => '16',
                    'bottom' => '12',
                    'left' => '16',
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .tc-table td' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'row_border',
            [
                'label' => esc_html__('Row Border', 'tablecrafter-wp-data-tables'),
                'type' => Controls_Manager::COLOR,
                'default' => '#e1e5e9',
                'selectors' => [
                    '{{WRAPPER}} .tc-table td' => 'border-bottom: 1px solid {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render the widget output on the frontend
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        
        // Generate unique ID for this widget instance
        $widget_id = 'tc-elementor-' . $this->get_id();
        
        // Build shortcode attributes
        $shortcode_atts = $this->build_shortcode_attributes($settings);
        
        // Output the table
        echo '<div class="tc-elementor-widget-wrapper" id="' . esc_attr($widget_id) . '">';
        
        if (empty($settings['data_source']['url'])) {
            // Show configuration prompt in editor
            if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                echo '<div style="padding: 40px; text-align: center; background: #f8f9fa; border: 2px dashed #ddd; border-radius: 8px;">';
                echo '<h3 style="margin: 0 0 10px; color: #666;">TableCrafter Data Table</h3>';
                echo '<p style="margin: 0; color: #999;">Please configure your data source in the widget settings.</p>';
                echo '</div>';
            } else {
                echo '<p>Please configure the TableCrafter data source.</p>';
            }
        } else {
            // Render the actual table
            echo do_shortcode($shortcode_atts);
        }
        
        echo '</div>';
    }

    /**
     * Build shortcode attributes from widget settings
     */
    protected function build_shortcode_attributes($settings)
    {
        $atts = ['[tablecrafter'];
        
        // Data source
        if (!empty($settings['data_source']['url'])) {
            $atts[] = 'source="' . esc_attr($settings['data_source']['url']) . '"';
        }
        
        // Root path for JSON
        if (!empty($settings['root_path'])) {
            $atts[] = 'root="' . esc_attr($settings['root_path']) . '"';
        }
        
        // Column filters
        if (!empty($settings['include_columns'])) {
            $atts[] = 'include="' . esc_attr($settings['include_columns']) . '"';
        }
        
        if (!empty($settings['exclude_columns'])) {
            $atts[] = 'exclude="' . esc_attr($settings['exclude_columns']) . '"';
        }
        
        // Display options
        $atts[] = 'search="' . ($settings['enable_search'] === 'yes' ? 'true' : 'false') . '"';
        $atts[] = 'filters="' . ($settings['enable_filters'] === 'yes' ? 'true' : 'false') . '"';
        $atts[] = 'export="' . ($settings['enable_export'] === 'yes' ? 'true' : 'false') . '"';
        
        // Pagination
        if (!empty($settings['per_page'])) {
            $atts[] = 'per_page="' . intval($settings['per_page']) . '"';
        }
        
        // Sorting
        if (!empty($settings['sort_column'])) {
            $sort_order = !empty($settings['sort_order']) ? $settings['sort_order'] : 'asc';
            $atts[] = 'sort="' . esc_attr($settings['sort_column']) . ':' . esc_attr($sort_order) . '"';
        }
        
        // Auto-refresh
        if ($settings['auto_refresh'] === 'yes') {
            $atts[] = 'auto_refresh="true"';
            if (!empty($settings['refresh_interval'])) {
                $atts[] = 'refresh_interval="' . intval($settings['refresh_interval']) . '"';
            }
        }
        
        // Cache duration
        if (isset($settings['cache_duration'])) {
            $atts[] = 'cache="' . intval($settings['cache_duration']) . '"';
        }
        
        $atts[] = ']';
        
        return implode(' ', $atts);
    }

    /**
     * Render widget output in the editor (live preview)
     */
    protected function content_template()
    {
        ?>
        <#
        var widgetId = 'tc-elementor-' + view.getID();
        var dataSource = settings.data_source ? settings.data_source.url : '';
        #>
        
        <div class="tc-elementor-widget-wrapper" id="{{ widgetId }}">
            <# if ( ! dataSource ) { #>
                <div style="padding: 40px; text-align: center; background: #f8f9fa; border: 2px dashed #ddd; border-radius: 8px;">
                    <h3 style="margin: 0 0 10px; color: #666;">TableCrafter Data Table</h3>
                    <p style="margin: 0; color: #999;">Please configure your data source in the widget settings.</p>
                </div>
            <# } else { #>
                <div style="padding: 20px; text-align: center; background: #e3f2fd; border: 1px solid #2196f3; border-radius: 8px;">
                    <h4 style="margin: 0 0 10px; color: #1976d2;">📊 TableCrafter Data Table</h4>
                    <p style="margin: 0; font-size: 14px; color: #1976d2;">
                        <strong>Source:</strong> {{ dataSource }}<br>
                        <strong>Features:</strong>
                        <# if ( settings.enable_search === 'yes' ) { #>Search, <# } #>
                        <# if ( settings.enable_filters === 'yes' ) { #>Filters, <# } #>
                        <# if ( settings.enable_export === 'yes' ) { #>Export, <# } #>
                        <# if ( settings.auto_refresh === 'yes' ) { #>Auto-refresh<# } #>
                    </p>
                    <small style="color: #666;">Live table will be displayed on the frontend</small>
                </div>
            <# } #>
        </div>
        <?php
    }
}

/**
 * Register TableCrafter Elementor Widget
 */
function register_tc_elementor_widget()
{
    // Make sure Elementor is loaded
    if (!did_action('elementor/loaded')) {
        return;
    }

    // Register the widget
    \Elementor\Plugin::instance()->widgets_manager->register_widget_type(new TC_Elementor_Widget());
}
add_action('elementor/widgets/widgets_registered', 'register_tc_elementor_widget');

/**
 * Add TableCrafter category to Elementor
 */
function add_tc_elementor_category($elements_manager)
{
    $elements_manager->add_category(
        'tablecrafter',
        [
            'title' => esc_html__('TableCrafter', 'tablecrafter-wp-data-tables'),
            'icon' => 'eicon-table',
        ]
    );
}
add_action('elementor/elements/categories_registered', 'add_tc_elementor_category');