<?php
namespace Unlockafe_Addons\Widgets;

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

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

/**
 * Elementor Dynamic Table Widget.
 *
 * @since 1.0.0
 */
class Dynamic_Table extends Widget_Base
{

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

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

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

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

    public function get_keywords()
    {
        return ['unlock', 'dynamic', 'table', 'sheet', 'google sheet', 'pdf', 'csv', 'json', 'excel', 'data', 'export', 'sync', 'tablepress', 'ninja tables'];
    }

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

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

    protected function register_controls()
    {
        /**
         * ------------------------------------------------
         * Content Section - Data Source
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_content_source',
            [
                'label' => esc_html__('Data Source', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'source_type',
            [
                'label' => esc_html__('Source Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'google_sheet',
                'options' => [
                    'google_sheet' => esc_html__('Google Sheet', 'unlock-addons-for-elementor'),
                    'csv' => esc_html__('CSV File URL', 'unlock-addons-for-elementor'),
                    'json' => esc_html__('JSON API', 'unlock-addons-for-elementor'),
                ],
            ]
        );

        $this->add_control(
            'google_sheet_url',
            [
                'label' => esc_html__('Google Sheet URL', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::URL,
                'placeholder' => 'https://docs.google.com/spreadsheets/d/your-sheet-id/edit?usp=sharing',
                'label_block' => true,
                'dynamic' => [
                    'active' => true,
                ],
                'condition' => [
                    'source_type' => 'google_sheet',
                ],
                'description' => esc_html__('Make sure your Google Sheet is public ("Anyone with the link can view").', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'csv_url',
            [
                'label' => esc_html__('CSV File URL', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::URL,
                'placeholder' => 'https://example.com/data.csv',
                'label_block' => true,
                'dynamic' => [
                    'active' => true,
                ],
                'condition' => [
                    'source_type' => 'csv',
                ],
            ]
        );

        $this->add_control(
            'json_url',
            [
                'label' => esc_html__('JSON API URL', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::URL,
                'placeholder' => 'https://api.example.com/data.json',
                'label_block' => true,
                'dynamic' => [
                    'active' => true,
                ],
                'condition' => [
                    'source_type' => 'json',
                ],
            ]
        );

        $this->add_control(
            'sheet_tab_name',
            [
                'label' => esc_html__('Sheet Name / Tab Name', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => esc_html__('Sheet1', 'unlock-addons-for-elementor'),
                'condition' => [
                    'source_type' => 'google_sheet',
                ],
                'description' => esc_html__('Enter the exact name of the tab in your Google Sheet.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'sheet_range',
            [
                'label' => esc_html__('Sheet Range (Optional)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'condition' => [
                    'source_type' => 'google_sheet',
                ],
                'placeholder' => 'A1:D10',
                'description' => esc_html__('Specify a cell range to fetch, e.g., A1:G10. If left empty, it will fetch the entire sheet.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'live_sync',
            [
                'label' => esc_html__('Live Data Sync', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Automatically sync data from your source at specified intervals.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Content Section - Table Features
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_content_features',
            [
                'label' => esc_html__('Table Features', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'show_search',
            [
                'label' => esc_html__('Enable Search', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_sorting',
            [
                'label' => esc_html__('Enable Column Sorting', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_pagination',
            [
                'label' => esc_html__('Enable Pagination', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'entries_per_page',
            [
                'label' => esc_html__('Entries Per Page', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 500,
                'step' => 1,
                'default' => 10,
                'condition' => [
                    'show_pagination' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'show_info',
            [
                'label' => esc_html__('Show Info Block', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Shows "Showing X to Y of Z entries" information.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'show_length_menu',
            [
                'label' => esc_html__('Show Length Menu', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Shows dropdown to change entries per page.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'show_export',
            [
                'label' => esc_html__('Enable Export Buttons', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'export_formats',
            [
                'label' => esc_html__('Export Formats', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => [
                    'csv' => esc_html__('CSV', 'unlock-addons-for-elementor'),
                    'excel' => esc_html__('Excel', 'unlock-addons-for-elementor'),
                    'pdf' => esc_html__('PDF', 'unlock-addons-for-elementor'),
                    'json' => esc_html__('JSON', 'unlock-addons-for-elementor'),
                ],
                'default' => ['csv', 'excel', 'pdf', 'json'],
                'condition' => [
                    'show_export' => 'yes',
                ],
                'label_block' => true,
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Content Section - Media Support
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_content_media',
            [
                'label' => esc_html__('Media Support', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'auto_detect_images',
            [
                'label' => esc_html__('Auto-detect Images', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Automatically convert image URLs to images.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'auto_detect_videos',
            [
                'label' => esc_html__('Auto-detect Videos', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Automatically embed YouTube/Vimeo videos.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'image_size',
            [
                'label' => esc_html__('Image Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'medium',
                'options' => [
                    'small' => esc_html__('Small (50px)', 'unlock-addons-for-elementor'),
                    'medium' => esc_html__('Medium (100px)', 'unlock-addons-for-elementor'),
                    'large' => esc_html__('Large (150px)', 'unlock-addons-for-elementor'),
                ],
                'condition' => [
                    'auto_detect_images' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'enable_lightbox',
            [
                'label' => esc_html__('Enable Image Lightbox', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'auto_detect_images' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Style Section - General
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_style_general',
            [
                'label' => esc_html__('General', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );
        $this->add_control(
            'table_theme',
            [
                'label' => esc_html__('Table Theme', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'striped-style',
                'options' => [
                    'default-style' => esc_html__('Default (Card Rows)', 'unlock-addons-for-elementor'),
                    'default-dark-style' => esc_html__('Default Dark (Neon)', 'unlock-addons-for-elementor'),
                    'striped-style' => esc_html__('Striped (Bold Header)', 'unlock-addons-for-elementor'),
                    'bordered-style' => esc_html__('Bordered (Dashed)', 'unlock-addons-for-elementor'),
                    'hover-style' => esc_html__('Hover (Lift & Glow)', 'unlock-addons-for-elementor'),
                    'compact-style' => esc_html__('Compact (Monospace)', 'unlock-addons-for-elementor'),
                    'gradient-style' => esc_html__('Gradient (Row Gradient)', 'unlock-addons-for-elementor'),
                    'minimal-style' => esc_html__('Minimal (Spacious)', 'unlock-addons-for-elementor'),
                    'minimal-dark-style' => esc_html__('Minimal Dark', 'unlock-addons-for-elementor'),
                    'minimal-elegant-style' => esc_html__('Minimal Elegant (Serif)', 'unlock-addons-for-elementor'),
                    'dark-style' => esc_html__('Dark (Blue Tint)', 'unlock-addons-for-elementor'),
                    'uppercase-heading-style' => esc_html__('Uppercase Heading (Industrial)', 'unlock-addons-for-elementor'),
                    'dark-knight-style' => esc_html__('Dark Knight (Gold Accent)', 'unlock-addons-for-elementor'),
                ],
            ]
        );

        $this->add_responsive_control(
            'table_width',
            [
                'label' => esc_html__('Table Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range' => [
                    '%' => [
                        'min' => 25,
                        'max' => 100,
                    ],
                    'px' => [
                        'min' => 200,
                        'max' => 1500,
                    ],
                ],
                'default' => [
                    'unit' => '%',
                    'size' => 100,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'table_box_shadow',
                'label' => esc_html__('Table Shadow', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlockafe-dynamic-table',
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Style Section - Header
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_style_header',
            [
                'label' => esc_html__('Table Header', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

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

        $this->add_control(
            'header_text_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper th' => 'color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'header_bg_color',
            [
                'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper th' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_responsive_control(
            'header_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper th' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Style Section - Body
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_style_body',
            [
                'label' => esc_html__('Table Body', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'body_typography',
                'selector' => '{{WRAPPER}} .unlockafe-dynamic-table-wrapper td',
            ]
        );

        $this->add_control(
            'body_text_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper td' => 'color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'body_bg_color',
            [
                'label' => esc_html__('Background Color (Odd Rows)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper tr:nth-child(odd) td' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'body_bg_color_even',
            [
                'label' => esc_html__('Background Color (Even Rows)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper tr:nth-child(even) td' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'body_hover_bg_color',
            [
                'label' => esc_html__('Hover Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper tbody tr:hover td' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_responsive_control(
            'body_padding',
            [
                'label' => esc_html__('Cell Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-dynamic-table-wrapper td' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'cell_border',
                'label' => esc_html__('Cell Border', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlockafe-dynamic-table-wrapper td, {{WRAPPER}} .unlockafe-dynamic-table-wrapper th',
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Style Section - Controls
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_style_controls',
            [
                'label' => esc_html__('Table Controls', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'search_bg_color',
            [
                'label' => esc_html__('Search Background', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .dataTables_filter input' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'search_text_color',
            [
                'label' => esc_html__('Search Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .dataTables_filter input' => 'color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'pagination_bg_color',
            [
                'label' => esc_html__('Pagination Background', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .dataTables_paginate .paginate_button' => 'background-color: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'pagination_text_color',
            [
                'label' => esc_html__('Pagination Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .dataTables_paginate .paginate_button' => 'color: {{VALUE}}',
                ],
            ]
        );

        // $this->add_control(
        //     'export_button_bg_color',
        //     [
        //         'label' => esc_html__('Export Button Background', 'unlock-addons-for-elementor'),
        //         'type' => Controls_Manager::COLOR,
        //         'selectors' => [
        //             '{{WRAPPER}} .ua-export-buttons .ua-export-btn' => 'background-color: {{VALUE}}',
        //         ],
        //     ]
        // );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Advanced Section
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_advanced_settings',
            [
                'label' => esc_html__('Advanced Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_ADVANCED,
            ]
        );

        $this->add_control(
            'cache_duration',
            [
                'label' => esc_html__('Cache/Sync Duration (Minutes)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'min' => 0,
                'max' => 1440, // 24 hours
                'step' => 1,
                'default' => 60,
                'description' => esc_html__('How often to sync with the data source. Set to 0 to disable cache and sync on every page load (not recommended).', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'responsive_mode',
            [
                'label' => esc_html__('Responsive Mode', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'scroll',
                'options' => [
                    'scroll' => esc_html__('Horizontal Scroll', 'unlock-addons-for-elementor'),
                    'stack' => esc_html__('Stack', 'unlock-addons-for-elementor'),
                    'responsive' => esc_html__('Responsive (DataTables)', 'unlock-addons-for-elementor'),
                ],
                'description' => esc_html__('"Stack" will display each row as a block on mobile devices.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'hide_columns_mobile',
            [
                'label' => esc_html__('Hide Columns on Mobile', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => esc_html__('1, 3, 5', 'unlock-addons-for-elementor'),
                'description' => esc_html__('Enter column numbers to hide on mobile, separated by commas (e.g., 1, 3).', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'import_styles',
            [
                'label' => esc_html__('Import Styles from Google Sheet', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
                'description' => esc_html__('If enabled, cell background color and font styles will be imported. This may override some Style Tab settings.', 'unlock-addons-for-elementor'),
                'condition' => [
                    'source_type' => 'google_sheet',
                ],
            ]
        );

        $this->add_control(
            'detect_line_breaks',
            [
                'label' => esc_html__('Detect Line Breaks', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Convert line breaks from spreadsheet to HTML breaks.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'seo_friendly',
            [
                'label' => esc_html__('SEO Friendly', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => esc_html__('Optimize table structure for search engines.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'custom_css',
            [
                'label' => esc_html__('Custom CSS', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::CODE,
                'language' => 'css',
                'rows' => 10,
                'description' => esc_html__('Add custom CSS for advanced styling.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->end_controls_section();

        /**
         * ------------------------------------------------
         * Shortcode Section
         * ------------------------------------------------
         */
        $this->start_controls_section(
            'section_shortcode',
            [
                'label' => esc_html__('Shortcode', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'shortcode_info',
            [
                'type' => Controls_Manager::RAW_HTML,
                'raw' => sprintf(
                    esc_html__('Use this shortcode to display the table anywhere: %s', 'unlock-addons-for-elementor'),
                    '<code>[unlockafe_table id="' . $this->get_id() . '"]</code>'
                ),
                'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
            ]
        );

        $this->end_controls_section();
    }

    private function get_google_sheet_csv_url($sheet_url, $sheet_tab_name, $sheet_range = '')
    {
        if (empty($sheet_url)) {
            return '';
        }

        if (preg_match('/spreadsheets\/d\/([a-zA-Z0-9-_]+)/', $sheet_url, $matches)) {
            $sheet_id = $matches[1];
            $csv_url = 'https://docs.google.com/spreadsheets/d/' . $sheet_id . '/gviz/tq?tqx=out:csv';
            if (!empty($sheet_tab_name)) {
                $csv_url .= '&sheet=' . rawurlencode($sheet_tab_name);
            }
            if (!empty($sheet_range)) {
                $csv_url .= '&range=' . rawurlencode($sheet_range);
            }
            return $csv_url;
        }

        return '';
    }

    private function parse_csv_data($csv_string)
    {
        $data = [];
        $lines = str_getcsv($csv_string, "\n");
        foreach ($lines as $line) {
            if (!empty(trim($line))) {
                $data[] = str_getcsv($line, ",");
            }
        }
        return $data;
    }

    private function parse_json_data($json_string)
    {
        $data = json_decode($json_string, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new \WP_Error('json_error', esc_html__('Invalid JSON data.', 'unlock-addons-for-elementor'));
        }

        // Convert associative array to indexed array for table display
        if (is_array($data) && !empty($data)) {
            $first_item = reset($data);
            if (is_array($first_item)) {
                // Add headers from first item keys
                $headers = array_keys($first_item);
                $table_data = [$headers];

                foreach ($data as $item) {
                    $row = [];
                    foreach ($headers as $header) {
                        $row[] = isset($item[$header]) ? $item[$header] : '';
                    }
                    $table_data[] = $row;
                }
                return $table_data;
            }
        }

        return $data;
    }

    private function process_cell_content($content, $settings)
    {
        // Detect line breaks
        if ($settings['detect_line_breaks'] === 'yes') {
            $content = nl2br($content);
        }

        // Auto-detect images
        if ($settings['auto_detect_images'] === 'yes') {
            $content = $this->convert_images($content, $settings);
        }

        // Auto-detect videos
        if ($settings['auto_detect_videos'] === 'yes') {
            $content = $this->convert_videos($content);
        }

        return $content;
    }

    private function convert_images($content, $settings)
    {
        $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
        $pattern = '/https?:\/\/[^\s]+\.(' . implode('|', $image_extensions) . ')/i';

        // Get size values based on selection
        $sizes = [
            'small' => '50px',
            'medium' => '100px',
            'large' => '150px'
        ];

        $size = $settings['image_size'];
        $size_value = isset($sizes[$size]) ? $sizes[$size] : '100px';
        $size_class = 'ua-img-' . $size;
        $lightbox_attr = $settings['enable_lightbox'] === 'yes' ? 'data-lightbox="table-gallery"' : '';

        // Add inline styles for the image
        $inline_style = 'style="width: ' . $size_value . '; max-width: ' . $size_value . '; height: auto; display: block; margin: 0 auto;"';

        return preg_replace_callback($pattern, function ($matches) use ($size_class, $lightbox_attr, $inline_style) {
            $url = $matches[0];
            return '<img src="' . esc_url($url) . '" class="' . $size_class . '" ' . $inline_style . ' ' . $lightbox_attr . ' alt="Table Image" />';
        }, $content);
    }

    private function convert_videos($content)
    {
        // YouTube
        $content = preg_replace(
            '/https?:\/\/(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/',
            '<div class="ua-video-wrapper"><iframe src="https://www.youtube.com/embed/$3" frameborder="0" allowfullscreen></iframe></div>',
            $content
        );

        // Vimeo
        $content = preg_replace(
            '/https?:\/\/(www\.)?vimeo\.com\/([0-9]+)/',
            '<div class="ua-video-wrapper"><iframe src="https://player.vimeo.com/video/$2" frameborder="0" allowfullscreen></iframe></div>',
            $content
        );

        return $content;
    }

    private function get_table_data()
    {
        $settings = $this->get_settings_for_display();
        $source_type = $settings['source_type'];
        $cache_duration = !empty($settings['cache_duration']) ? absint($settings['cache_duration']) * MINUTE_IN_SECONDS : HOUR_IN_SECONDS;

        if ('google_sheet' === $source_type) {
            $url = $this->get_google_sheet_csv_url($settings['google_sheet_url']['url'], $settings['sheet_tab_name'], $settings['sheet_range']);
        } elseif ('json' === $source_type) {
            $url = $settings['json_url']['url'];
        } else {
            $url = $settings['csv_url']['url'];
        }

        if (empty($url)) {
            return new \WP_Error('invalid_url', esc_html__('Invalid data source URL.', 'unlock-addons-for-elementor'));
        }

        $transient_key = 'unlockafe_table_data_' . md5($url . serialize($settings));

        if ($settings['live_sync'] !== 'yes') {
            $cached_data = get_transient($transient_key);
            if (false !== $cached_data) {
                return $cached_data;
            }
        }

        $response = wp_remote_get($url, [
            'timeout' => 30,
            'headers' => [
                'User-Agent' => 'UnlockAFE Dynamic Table Widget'
            ]
        ]);

        if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            return new \WP_Error('fetch_error', esc_html__('Error fetching data from the source.', 'unlock-addons-for-elementor'));
        }

        $body = wp_remote_retrieve_body($response);

        if ('json' === $source_type) {
            $data = $this->parse_json_data($body);
        } else {
            $data = $this->parse_csv_data($body);
        }

        if (is_wp_error($data) || empty($data)) {
            return new \WP_Error('empty_data', esc_html__('No data found or failed to parse.', 'unlock-addons-for-elementor'));
        }

        return $data;
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $table_data = $this->get_table_data();
        $theme = $settings['table_theme'];

        $table_settings = [
            'showSearch' => ($settings['show_search'] === 'yes'),
            'showSorting' => ($settings['show_sorting'] === 'yes'),
            'showPagination' => ($settings['show_pagination'] === 'yes'),
            'showInfo' => ($settings['show_info'] === 'yes'),
            'showLengthMenu' => ($settings['show_length_menu'] === 'yes'),
            'entriesPerPage' => absint($settings['entries_per_page']),
            'showExport' => ($settings['show_export'] === 'yes'),
            'exportFormats' => $settings['export_formats'],
            'responsiveMode' => $settings['responsive_mode'],
            'hideColumnsMobile' => $settings['hide_columns_mobile'],
            'importStyles' => ($settings['import_styles'] === 'yes'),
            'theme' => $theme,
            'seoFriendly' => ($settings['seo_friendly'] === 'yes'),
            'liveSync' => ($settings['live_sync'] === 'yes'),
            'cacheDuration' => $settings['cache_duration'],
        ];

        $this->add_render_attribute(
            'wrapper',
            [
                'class' => ['unlockafe-dynamic-table-wrapper', $theme . '-wrapper'],
                'data-settings' => wp_json_encode($table_settings),
            ]
        );
        if (!empty($settings['custom_css'])) {
            echo '<style>' . $settings['custom_css'] . '</style>';
        }
        ?>
        <svg width="0" height="0" style="display:none;">
            <symbol id="icon-csv" viewBox="0 0 24 24" fill="currentColor">
                <path d="M5 14v-4h4v4H5zm6 0v-4h4v4h-4zM2 2v20h20V2H2zm18 18H4V4h16v16z" />
            </symbol>
            <symbol id="icon-excel" viewBox="0 0 24 24" fill="currentColor">
                <path
                    d="M21.17 3.25l-4.24 4.24.71.71 4.24-4.24-.71-.71zM10 18h4v-2h-4v2zm-6-4h4v-2H4v2zm0-4h4V8H4v2zm0-4h4V4H4v2zm6 8h4v-2h-4v2zm0-4h4V8h-4v2zm0-4h4V4h-4v2zm6 8h4v-2h-4v2zm0-4h4V8h-4v2z" />
            </symbol>
            <symbol id="icon-pdf" viewBox="0 0 24 24" fill="currentColor">
                <path
                    d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" />
            </symbol>
            <symbol id="icon-json" viewBox="0 0 24 24" fill="currentColor">
                <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z" />
            </symbol>
        </svg>
        <div <?php echo $this->get_render_attribute_string('wrapper'); ?>>
            <?php
            if (is_wp_error($table_data)) {
                if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                    echo '<div class="ua-error-message">' . esc_html($table_data->get_error_message()) . '</div>';
                }
                return;
            }

            if (empty($table_data)) {
                if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                    echo '<div class="ua-error-message">' . esc_html__('No data found.', 'unlock-addons-for-elementor') . '</div>';
                }
                return;
            }

            $header = array_shift($table_data);
            $header_count = count($header);
            $table_id = 'unlockafe-dynamic-table-' . \esc_attr($this->get_id());
            ?>
            <div class="table-controls <?php echo esc_attr($theme); ?>-controls">
                <div class="top-row">
                    <div class="left-controls">
                        <?php if ($settings['show_length_menu'] === 'yes'): ?>
                            <div class="dataTables_length">
                                <label>
                                    <?php esc_html_e('Show', 'unlock-addons-for-elementor'); ?>
                                    <select name="<?php echo esc_attr($table_id); ?>_length"
                                        aria-controls="<?php echo esc_attr($table_id); ?>">
                                        <option value="10">10</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                    <?php esc_html_e('entries', 'unlock-addons-for-elementor'); ?>
                                </label>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="right-controls">
                        <?php if ($settings['show_export'] === 'yes' && !empty($settings['export_formats'])): ?>
                            <div class="export-buttons">
                                <?php foreach ($settings['export_formats'] as $format): ?>
                                    <button class="ua-export-btn" data-format="<?php echo esc_attr($format); ?>">
                                        <svg>
                                            <use href="#icon-<?php echo esc_attr($format); ?>"></use>
                                        </svg>
                                        <span><?php echo esc_html(strtoupper($format)); ?></span>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if ($settings['show_search'] === 'yes'): ?>
                    <div class="bottom-row">
                        <div class="dataTables_filter">
                            <label>
                                <input type="search" class=""
                                    placeholder="<?php esc_attr_e('Search...', 'unlock-addons-for-elementor'); ?>"
                                    aria-controls="<?php echo esc_attr($table_id); ?>">
                            </label>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <div class="<?php echo esc_attr($theme); ?>-table-wrapper ua-table-container">
                <table id="<?php echo esc_attr($table_id); ?>"
                    class="unlockafe-dynamic-table <?php echo esc_attr($theme); ?>-table">
                    <thead>
                        <tr>
                            <?php foreach ($header as $col_header): ?>
                                <th scope="col"><?php echo esc_html($col_header); ?></th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($table_data as $row): ?>
                            <tr>
                                <?php
                                $row_count = count($row);
                                if ($row_count < $header_count) {
                                    $row = array_pad($row, $header_count, '');
                                } elseif ($row_count > $header_count) {
                                    $row = array_slice($row, 0, $header_count);
                                }
                                foreach ($row as $cell_index => $cell):
                                    $original_content = $cell;
                                    $processed_content = $this->process_cell_content($original_content, $settings);
                                    ?>
                                    <td data-label="<?php echo esc_attr($header[$cell_index]); ?>"
                                        data-original-content="<?php echo esc_attr($original_content); ?>">
                                        <?php
                                        echo $processed_content;
                                        ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($settings['show_pagination'] === 'yes' || $settings['show_info'] === 'yes'): ?>
                <div class="table-footer <?php echo esc_attr($theme); ?>-footer">
                    <?php if ($settings['show_info'] === 'yes'): ?>
                        <div class="footer-info dataTables_info"></div>
                    <?php endif; ?>
                    <?php if ($settings['show_pagination'] === 'yes'): ?>
                        <div class="pagination-wrapper <?php echo esc_attr($theme); ?>-pagination dataTables_paginate"></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
}
