<?php

namespace Calio\Widgets;

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

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

/**
 * Data table widget with custom HTML, static rows, CSV and Google Sheet sources.
 */
class TableWidget extends BaseWidget
{
    public function get_name(): string
    {
        return 'calio-table';
    }

    public function get_title(): string
    {
        return esc_html__('Table', 'calio-addon');
    }

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

    public function get_style_depends(): array
    {
        return $this->resolve_widget_style_depends('calio-widget-table');
    }

    public function get_script_depends(): array
    {
        return $this->resolve_widget_script_depends('calio-widget-table');
    }

    public function get_keywords(): array
    {
        return array_merge(parent::get_keywords(), ['table', 'csv', 'sheet', 'data']);
    }

    protected function register_controls(): void
    {
        $this->register_table_content_controls();
        $this->register_datatable_controls();
        $this->register_table_style_controls();
        $this->register_header_style_controls();
        $this->register_body_style_controls();
        $this->register_filter_style_controls();
    }

    private function register_table_content_controls(): void
    {
        $this->start_controls_section(
            'section_table_content',
            [
                'label' => esc_html__('Table', 'calio-addon'),
            ]
        );

        $this->add_control(
            'data_source',
            [
                'label' => esc_html__('Table Type', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => 'custom_html',
                'options' => [
                    'custom_html' => esc_html__('Custom HTML Table', 'calio-addon'),
                    'static_source' => esc_html__('Static Data', 'calio-addon'),
                    'csv_source' => esc_html__('CSV File', 'calio-addon'),
                    'google_sheet' => esc_html__('Google Sheet', 'calio-addon'),
                ],
            ]
        );

        $this->add_control(
            'caption',
            [
                'label' => esc_html__('Caption', 'calio-addon'),
                'type' => Controls_Manager::TEXT,
                'dynamic' => ['active' => true],
                'default' => esc_html__('Comparison Table', 'calio-addon'),
            ]
        );

        $this->add_control(
            'hide_header',
            [
                'label' => esc_html__('Hide Header', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_control(
            'header_alignment',
            [
                'label' => esc_html__('Header Alignment', 'calio-addon'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => esc_html__('Left', 'calio-addon'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'calio-addon'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => esc_html__('Right', 'calio-addon'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'left',
                'toggle' => false,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget thead th' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'body_alignment',
            [
                'label' => esc_html__('Body Alignment', 'calio-addon'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => esc_html__('Left', 'calio-addon'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'calio-addon'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => esc_html__('Right', 'calio-addon'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'left',
                'toggle' => false,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget tbody td' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'support_type',
            [
                'label' => esc_html__('Support Type', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => 'default',
                'options' => [
                    'default' => esc_html__('Default', 'calio-addon'),
                    'smooth' => esc_html__('Smooth', 'calio-addon'),
                    'minimal' => esc_html__('Minimal', 'calio-addon'),
                ],
            ]
        );

        $this->add_control(
            'static_type',
            [
                'label' => esc_html__('Static Type', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => 'default',
                'options' => [
                    'default' => esc_html__('Default', 'calio-addon'),
                    'pricing' => esc_html__('Pricing', 'calio-addon'),
                    'feature' => esc_html__('Feature Matrix', 'calio-addon'),
                ],
                'condition' => [
                    'data_source!' => 'custom_html',
                ],
            ]
        );

        $this->add_control(
            'responsive_scroll',
            [
                'label' => esc_html__('Responsive', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'enable_datatable',
            [
                'label' => esc_html__('Datatable', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'custom_table_html',
            [
                'label' => esc_html__('Table HTML Tag', 'calio-addon'),
                'type' => Controls_Manager::WYSIWYG,
                'default' => $this->default_custom_table_markup(),
                'condition' => [
                    'data_source' => 'custom_html',
                ],
            ]
        );

        $this->add_control(
            'csv_file',
            [
                'label' => esc_html__('CSV File', 'calio-addon'),
                'type' => Controls_Manager::MEDIA,
                'media_types' => ['application'],
                'dynamic' => ['active' => true],
                'condition' => [
                    'data_source' => 'csv_source',
                ],
            ]
        );

        $this->add_control(
            'csv_delimiter',
            [
                'label' => esc_html__('CSV Delimiter', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => ',',
                'options' => [
                    ',' => esc_html__('Comma (,)', 'calio-addon'),
                    ';' => esc_html__('Semicolon (;)', 'calio-addon'),
                    "\t" => esc_html__('Tab', 'calio-addon'),
                ],
                'condition' => [
                    'data_source' => ['csv_source', 'google_sheet'],
                ],
            ]
        );

        $this->add_control(
            'google_sheet_url',
            [
                'label' => esc_html__('Google Sheet URL', 'calio-addon'),
                'type' => Controls_Manager::URL,
                'placeholder' => esc_url('https://docs.google.com/spreadsheets/d/...'),
                'condition' => [
                    'data_source' => 'google_sheet',
                ],
            ]
        );

        $this->add_control(
            'static_allow_html',
            [
                'label' => esc_html__('Allow HTML in Static Cells', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
                'condition' => [
                    'data_source' => 'static_source',
                ],
            ]
        );

        $columnRepeater = new Repeater();
        $columnRepeater->add_control(
            'title',
            [
                'label' => esc_html__('Column Title', 'calio-addon'),
                'type' => Controls_Manager::TEXT,
                'label_block' => true,
                'default' => esc_html__('Column', 'calio-addon'),
            ]
        );

        $this->add_control(
            'static_columns',
            [
                'label' => esc_html__('Columns', 'calio-addon'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $columnRepeater->get_controls(),
                'title_field' => '{{{ title }}}',
                'condition' => [
                    'data_source' => 'static_source',
                ],
                'default' => [
                    ['title' => esc_html__('Plan', 'calio-addon')],
                    ['title' => esc_html__('Starter', 'calio-addon')],
                    ['title' => esc_html__('Business', 'calio-addon')],
                    ['title' => esc_html__('Enterprise', 'calio-addon')],
                ],
            ]
        );

        $rowRepeater = new Repeater();
        $rowRepeater->add_control(
            'cells',
            [
                'label' => esc_html__('Cells', 'calio-addon'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => esc_html__('Projects|3|10|Unlimited', 'calio-addon'),
                'description' => esc_html__('Use "|" to split each cell. Example: Feature|Basic|Pro', 'calio-addon'),
            ]
        );
        $rowRepeater->add_control(
            'highlight',
            [
                'label' => esc_html__('Highlight Row', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_control(
            'static_rows',
            [
                'label' => esc_html__('Rows', 'calio-addon'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $rowRepeater->get_controls(),
                'title_field' => '{{{ cells }}}',
                'condition' => [
                    'data_source' => 'static_source',
                ],
                'default' => [
                    ['cells' => esc_html__('Price|$19|$49|$99', 'calio-addon')],
                    ['cells' => esc_html__('Projects|3|15|Unlimited', 'calio-addon')],
                    ['cells' => esc_html__('Priority Support|No|Email|Dedicated', 'calio-addon'), 'highlight' => 'yes'],
                    ['cells' => esc_html__('Storage|20 GB|200 GB|2 TB', 'calio-addon')],
                ],
            ]
        );

        $this->end_controls_section();
    }

    private function register_datatable_controls(): void
    {
        $this->start_controls_section(
            'section_data_table_settings',
            [
                'label' => esc_html__('Data Table Settings', 'calio-addon'),
                'condition' => [
                    'enable_datatable' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'datatable_search',
            [
                'label' => esc_html__('Search', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'datatable_ordering',
            [
                'label' => esc_html__('Ordering', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'datatable_pagination',
            [
                'label' => esc_html__('Pagination', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'datatable_info',
            [
                'label' => esc_html__('Info', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'datatable_length_menu',
            [
                'label' => esc_html__('Show Entries Menu', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'datatable_pagination' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'datatable_length_custom_input',
            [
                'label' => esc_html__('Custom Row Input', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'datatable_pagination' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'rows_per_page',
            [
                'label' => esc_html__('Rows Per Page', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 8,
                'min' => 1,
                'max' => 200,
                'condition' => [
                    'datatable_pagination' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'rows_per_page_min',
            [
                'label' => esc_html__('Min Rows', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 1,
                'min' => 1,
                'condition' => [
                    'datatable_pagination' => 'yes',
                    'datatable_length_custom_input' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'rows_per_page_max',
            [
                'label' => esc_html__('Max Rows', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 200,
                'min' => 1,
                'condition' => [
                    'datatable_pagination' => 'yes',
                    'datatable_length_custom_input' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'search_placeholder',
            [
                'label' => esc_html__('Search Placeholder', 'calio-addon'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('Search table...', 'calio-addon'),
                'condition' => [
                    'datatable_search' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();
    }

    private function register_table_style_controls(): void
    {
        $this->start_controls_section(
            'section_style_table',
            [
                'label' => esc_html__('Table', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'stripe_style',
            [
                'label' => esc_html__('Stripe Style', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'remove_vertical_border',
            [
                'label' => esc_html__('Remove Vertical Border', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_control(
            'leading_column_style',
            [
                'label' => esc_html__('Leading Column Style', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $this->add_control(
            'row_hover',
            [
                'label' => esc_html__('Hover Color', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

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

        $this->add_control(
            'table_border_color_manual',
            [
                'label' => esc_html__('Border Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget table th, {{WRAPPER}} .calio-table-widget table td' => 'border-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_dimensions_control(
            'table_cell_padding',
            esc_html__('Cell Padding', 'calio-addon'),
            [
                '{{WRAPPER}} .calio-table-widget table th',
                '{{WRAPPER}} .calio-table-widget table td',
            ],
            'padding'
        );

        $this->add_dimensions_control(
            'table_radius',
            esc_html__('Radius', 'calio-addon'),
            [
                '{{WRAPPER}} .calio-table-widget',
                '{{WRAPPER}} .calio-table-widget table',
            ],
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->add_dimensions_control(
            'table_padding',
            esc_html__('Wrapper Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget',
            'padding'
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'table_wrapper_border',
                'selector' => '{{WRAPPER}} .calio-table-widget',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'table_wrapper_shadow',
                'selector' => '{{WRAPPER}} .calio-table-widget',
            ]
        );

        $this->end_controls_section();
    }

    private function register_header_style_controls(): void
    {
        $this->start_controls_section(
            'section_style_header',
            [
                'label' => esc_html__('Header', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'header_bg_color',
            [
                'label' => esc_html__('Background Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget thead th' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'header_text_color',
            [
                'label' => esc_html__('Text Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget thead th' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'header_border',
                'selector' => '{{WRAPPER}} .calio-table-widget thead th',
            ]
        );

        $this->add_dimensions_control(
            'header_radius',
            esc_html__('Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget thead th',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->add_dimensions_control(
            'header_padding',
            esc_html__('Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget thead th',
            'padding'
        );

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

        $this->end_controls_section();
    }

    private function register_body_style_controls(): void
    {
        $this->start_controls_section(
            'section_style_body',
            [
                'label' => esc_html__('Body', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->start_controls_tabs('body_style_tabs');

        $this->start_controls_tab(
            'body_style_tab_normal',
            [
                'label' => esc_html__('Normal', 'calio-addon'),
            ]
        );

        $this->add_control(
            'body_text_color',
            [
                'label' => esc_html__('Text Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget tbody td' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'body_bg_color',
            [
                'label' => esc_html__('Background Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget tbody td' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'row_even_bg',
            [
                'label' => esc_html__('Stripe Background', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget.has-stripe tbody tr:nth-child(even) td' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'body_border',
                'selector' => '{{WRAPPER}} .calio-table-widget tbody td',
            ]
        );

        $this->add_dimensions_control(
            'body_radius',
            esc_html__('Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget tbody td',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->add_dimensions_control(
            'body_cell_padding',
            esc_html__('Cell Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget tbody td',
            'padding'
        );

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

        $this->end_controls_tab();

        $this->start_controls_tab(
            'body_style_tab_hover',
            [
                'label' => esc_html__('Hover', 'calio-addon'),
            ]
        );

        $this->add_control(
            'row_hover_text',
            [
                'label' => esc_html__('Text Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget.has-row-hover tbody tr:hover td' => 'color: {{VALUE}};',
                ],
                'condition' => [
                    'row_hover' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'row_hover_bg',
            [
                'label' => esc_html__('Background Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget.has-row-hover tbody tr:hover td' => 'background-color: {{VALUE}};',
                ],
                'condition' => [
                    'row_hover' => 'yes',
                ],
            ]
        );

        $this->end_controls_tab();
        $this->end_controls_tabs();

        $this->end_controls_section();
    }

    private function register_filter_style_controls(): void
    {
        $this->start_controls_section(
            'section_style_filter',
            [
                'label' => esc_html__('Filter', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'enable_datatable' => 'yes',
                ],
            ]
        );

        $this->start_controls_tabs('table_filter_style_tabs');

        $this->start_controls_tab(
            'table_filter_style_header',
            [
                'label' => esc_html__('Header', 'calio-addon'),
            ]
        );

        $this->add_control(
            'filter_header_text_color',
            [
                'label' => esc_html__('Text Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-search-label' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'filter_input_text_color',
            [
                'label' => esc_html__('Input Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-search' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'filter_input_bg',
            [
                'label' => esc_html__('Input Background', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-search' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_dimensions_control(
            'filter_input_padding',
            esc_html__('Input Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget .calio-table-search',
            'padding'
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'filter_input_border',
                'selector' => '{{WRAPPER}} .calio-table-widget .calio-table-search',
            ]
        );

        $this->add_dimensions_control(
            'filter_input_radius',
            esc_html__('Input Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-table-widget .calio-table-search',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'filter_input_shadow',
                'selector' => '{{WRAPPER}} .calio-table-widget .calio-table-search',
            ]
        );

        $this->add_control(
            'filter_header_space',
            [
                'label' => esc_html__('Space', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-filter-header' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'table_filter_style_footer',
            [
                'label' => esc_html__('Footer', 'calio-addon'),
            ]
        );

        $this->add_control(
            'filter_footer_text_color',
            [
                'label' => esc_html__('Text Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-info' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'pagination_color',
            [
                'label' => esc_html__('Pagination Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-page' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'pagination_alignment',
            [
                'label' => esc_html__('Pagination Alignment', 'calio-addon'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'flex-start' => [
                        'title' => esc_html__('Left', 'calio-addon'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'calio-addon'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'flex-end' => [
                        'title' => esc_html__('Right', 'calio-addon'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'flex-end',
                'toggle' => false,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-pagination' => 'justify-content: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'pagination_active_color',
            [
                'label' => esc_html__('Pagination Active Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-page.is-active' => 'color: #ffffff; background-color: {{VALUE}}; border-color: {{VALUE}};',
                    '{{WRAPPER}} .calio-table-widget .calio-table-page:hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'filter_footer_space',
            [
                'label' => esc_html__('Space', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-table-widget .calio-table-filter-footer' => 'margin-top: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();
        $this->end_controls_tabs();

        $this->end_controls_section();
    }

    protected function render(): void
    {
        $settings = $this->get_settings_for_display();
        $source = sanitize_key((string) ($settings['data_source'] ?? 'custom_html'));
        if (!in_array($source, ['custom_html', 'static_source', 'csv_source', 'google_sheet'], true)) {
            $source = 'custom_html';
        }
        $supportType = sanitize_key((string) ($settings['support_type'] ?? 'default'));
        if (!in_array($supportType, ['default', 'smooth', 'minimal'], true)) {
            $supportType = 'default';
        }
        $staticType = sanitize_key((string) ($settings['static_type'] ?? 'default'));
        if (!in_array($staticType, ['default', 'pricing', 'feature'], true)) {
            $staticType = 'default';
        }

        $useScroll = $this->is_enabled($settings, 'responsive_scroll', true);
        $isDatatable = $this->is_enabled($settings, 'enable_datatable');
        $showSearch = $this->is_enabled($settings, 'datatable_search');
        $showOrdering = $this->is_enabled($settings, 'datatable_ordering');
        $showPagination = $this->is_enabled($settings, 'datatable_pagination');
        $showInfo = $this->is_enabled($settings, 'datatable_info');
        $showLengthMenu = $this->is_enabled($settings, 'datatable_length_menu', true);
        $showLengthInput = $this->is_enabled($settings, 'datatable_length_custom_input', true);
        $hideHeader = $this->is_enabled($settings, 'hide_header');
        $rowsPerPage = max(1, min(200, (int) ($settings['rows_per_page'] ?? 8)));
        $rowsMin = max(1, min(200, (int) ($settings['rows_per_page_min'] ?? 1)));
        $rowsMax = max($rowsMin, min(500, (int) ($settings['rows_per_page_max'] ?? 200)));

        $classes = [
            'calio-table-widget',
            'source-' . $source,
            'support-' . $supportType,
            'static-' . $staticType,
        ];

        if ($this->is_enabled($settings, 'stripe_style', true)) {
            $classes[] = 'has-stripe';
        }
        if ($this->is_enabled($settings, 'remove_vertical_border')) {
            $classes[] = 'no-vertical-border';
        }
        if ($this->is_enabled($settings, 'leading_column_style')) {
            $classes[] = 'has-leading-column';
        }
        if ($this->is_enabled($settings, 'row_hover', true)) {
            $classes[] = 'has-row-hover';
        }
        if ($useScroll) {
            $classes[] = 'is-responsive';
        }
        if ($hideHeader) {
            $classes[] = 'is-hide-header';
        }
        if ($isDatatable) {
            $classes[] = 'has-datatable';
        }

        $attributes = [
            'class' => implode(' ', $classes),
            'data-datatable' => $isDatatable ? 'yes' : 'no',
            'data-search' => $showSearch ? 'yes' : 'no',
            'data-ordering' => $showOrdering ? 'yes' : 'no',
            'data-pagination' => $showPagination ? 'yes' : 'no',
            'data-info' => $showInfo ? 'yes' : 'no',
            'data-length-menu' => ($showPagination && $showLengthMenu) ? 'yes' : 'no',
            'data-length-custom' => ($showPagination && $showLengthInput) ? 'yes' : 'no',
            'data-page-size' => (string) $rowsPerPage,
            'data-page-size-min' => (string) $rowsMin,
            'data-page-size-max' => (string) $rowsMax,
        ];

        echo '<div ' . wp_kses_data($this->render_attributes($attributes)) . '>';

        if (!empty($settings['caption'])) {
            echo '<div class="calio-table-caption">' . esc_html((string) $settings['caption']) . '</div>';
        }

        if ($isDatatable && ($showSearch || ($showPagination && ($showLengthMenu || $showLengthInput)))) {
            echo '<div class="calio-table-filter calio-table-filter-header">';

            if ($showPagination && ($showLengthMenu || $showLengthInput)) {
                echo '<div class="calio-table-controls-left">';

                if ($showLengthMenu) {
                    $lengthOptions = [5, 10, 25, 50, 100];
                    if (!in_array($rowsPerPage, $lengthOptions, true)) {
                        $lengthOptions[] = $rowsPerPage;
                        sort($lengthOptions);
                    }

                    echo '<label class="calio-table-length-wrap">';
                    echo '<span class="calio-table-length-label">' . esc_html__('Show', 'calio-addon') . '</span>';
                    echo '<select class="calio-table-length" aria-label="' . esc_attr__('Rows per page', 'calio-addon') . '">';
                    foreach ($lengthOptions as $option) {
                        echo '<option value="' . esc_attr((string) $option) . '"' . selected($rowsPerPage, $option, false) . '>' . esc_html((string) $option) . '</option>';
                    }
                    echo '</select>';
                    echo '<span class="calio-table-length-label">' . esc_html__('entries', 'calio-addon') . '</span>';
                    echo '</label>';
                }

                if ($showLengthInput) {
                    echo '<label class="calio-table-length-custom-wrap">';
                    echo '<span class="calio-table-length-label">' . esc_html__('Rows', 'calio-addon') . '</span>';
                    echo '<input type="number" class="calio-table-length-custom" min="' . esc_attr((string) $rowsMin) . '" max="' . esc_attr((string) $rowsMax) . '" value="' . esc_attr((string) $rowsPerPage) . '" />';
                    echo '</label>';
                }

                echo '</div>';
            }

            if ($showSearch) {
                $placeholder = (string) ($settings['search_placeholder'] ?? esc_html__('Search table...', 'calio-addon'));
                echo '<div class="calio-table-controls-right">';
                echo '<label class="calio-table-search-wrap">';
                echo '<span class="calio-table-search-label">' . esc_html__('Search', 'calio-addon') . '</span>';
                echo '<input type="search" class="calio-table-search" placeholder="' . esc_attr($placeholder) . '" />';
                echo '</label>';
                echo '</div>';
            }

            echo '</div>';
        }

        if ($useScroll) {
            echo '<div class="calio-table-scroll">';
        }

        echo '<div class="calio-table-source">';
        if ($source === 'custom_html') {
            echo wp_kses_post($this->render_custom_source($settings));
        } elseif ($source === 'csv_source') {
            echo wp_kses_post($this->render_csv_table($settings, !$hideHeader));
        } elseif ($source === 'google_sheet') {
            echo wp_kses_post($this->render_google_sheet_table($settings, !$hideHeader));
        } else {
            echo wp_kses_post($this->render_static_table($settings, !$hideHeader));
        }
        echo '</div>';

        if ($useScroll) {
            echo '</div>';
        }

        if ($isDatatable && ($showInfo || $showPagination)) {
            echo '<div class="calio-table-filter calio-table-filter-footer">';
            if ($showInfo) {
                echo '<div class="calio-table-info" aria-live="polite"></div>';
            }
            if ($showPagination) {
                echo '<div class="calio-table-pagination" aria-label="' . esc_attr__('Table pagination', 'calio-addon') . '"></div>';
            }
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function render_custom_source(array $settings): string
    {
        $markup = trim((string) ($settings['custom_table_html'] ?? ''));
        if ($markup === '') {
            $markup = $this->default_custom_table_markup();
        }

        if (stripos($markup, '<table') === false) {
            return '<div class="calio-table-empty">' . esc_html__('Please add a valid <table> markup to render this source.', 'calio-addon') . '</div>';
        }

        $markup = $this->inject_table_class($markup);

        return '<div class="calio-table-custom-source">' . wp_kses_post($markup) . '</div>';
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function render_static_table(array $settings, bool $showHeader): string
    {
        $columns = isset($settings['static_columns']) && is_array($settings['static_columns']) ? $settings['static_columns'] : [];
        $rows = isset($settings['static_rows']) && is_array($settings['static_rows']) ? $settings['static_rows'] : [];
        $allowHtml = $this->is_enabled($settings, 'static_allow_html');

        if ($columns === [] || $rows === []) {
            return '<div class="calio-table-empty">' . esc_html__('Add columns and rows to show the table.', 'calio-addon') . '</div>';
        }

        $markup = '<table class="calio-table-element">';
        if ($showHeader) {
            $markup .= '<thead><tr>';
            foreach ($columns as $column) {
                $markup .= '<th scope="col">' . esc_html((string) ($column['title'] ?? '')) . '</th>';
            }
            $markup .= '</tr></thead>';
        }

        $markup .= '<tbody>';
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }

            $cells = $this->parse_cells((string) ($row['cells'] ?? ''));
            $rowClasses = [];
            if (($row['highlight'] ?? '') === 'yes') {
                $rowClasses[] = 'is-highlight';
            }

            $markup .= '<tr' . ($rowClasses ? ' class="' . esc_attr(implode(' ', $rowClasses)) . '"' : '') . '>';
            for ($index = 0; $index < count($columns); $index++) {
                $cellValue = $cells[$index] ?? '';
                if ($allowHtml) {
                    $markup .= '<td>' . wp_kses_post($cellValue) . '</td>';
                } else {
                    $markup .= '<td>' . esc_html($cellValue) . '</td>';
                }
            }
            $markup .= '</tr>';
        }
        $markup .= '</tbody></table>';

        return $markup;
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function render_csv_table(array $settings, bool $showHeader): string
    {
        $rows = $this->parse_csv_rows($settings);
        if ($rows === []) {
            return '<div class="calio-table-empty">' . esc_html__('Upload a valid CSV file to render the table.', 'calio-addon') . '</div>';
        }

        return $this->render_rows_to_table($rows, $showHeader);
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function render_google_sheet_table(array $settings, bool $showHeader): string
    {
        $rows = $this->parse_google_sheet_rows($settings);
        if ($rows === []) {
            return '<div class="calio-table-empty">' . esc_html__('Add a public Google Sheet URL to render table data.', 'calio-addon') . '</div>';
        }

        return $this->render_rows_to_table($rows, $showHeader);
    }

    /**
     * @param array<int, array<int, string>> $rows
     */
    private function render_rows_to_table(array $rows, bool $showHeader): string
    {
        $header = $showHeader ? array_shift($rows) : null;
        $markup = '<table class="calio-table-element">';

        if ($showHeader && is_array($header)) {
            $markup .= '<thead><tr>';
            foreach ($header as $column) {
                $markup .= '<th scope="col">' . esc_html((string) $column) . '</th>';
            }
            $markup .= '</tr></thead>';
        }

        $markup .= '<tbody>';
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }

            $markup .= '<tr>';
            foreach ($row as $cell) {
                $markup .= '<td>' . esc_html((string) $cell) . '</td>';
            }
            $markup .= '</tr>';
        }
        $markup .= '</tbody></table>';

        return $markup;
    }

    /**
     * @param array<string, mixed> $settings
     * @return array<int, array<int, string>>
     */
    private function parse_csv_rows(array $settings): array
    {
        $delimiter = $this->resolve_delimiter($settings);
        $content = '';

        $attachmentId = (int) ($settings['csv_file']['id'] ?? 0);
        if ($attachmentId > 0) {
            $attachmentUrl = wp_get_attachment_url($attachmentId);
            if (is_string($attachmentUrl) && $attachmentUrl !== '') {
                $content = $this->fetch_remote_content($attachmentUrl);
            }
        }

        if ($content === '' && !empty($settings['csv_file']['url'])) {
            $content = $this->fetch_remote_content((string) $settings['csv_file']['url']);
        }

        return $this->parse_delimited_rows($content, $delimiter);
    }

    /**
     * @param array<string, mixed> $settings
     * @return array<int, array<int, string>>
     */
    private function parse_google_sheet_rows(array $settings): array
    {
        $rawUrl = (string) ($settings['google_sheet_url']['url'] ?? '');
        if ($rawUrl === '') {
            return [];
        }

        $csvUrl = $this->resolve_google_sheet_csv_url($rawUrl);
        $content = $this->fetch_remote_content($csvUrl);

        return $this->parse_delimited_rows($content, $this->resolve_delimiter($settings));
    }

    /**
     * @return array<int, array<int, string>>
     */
    private function parse_delimited_rows(string $content, string $delimiter): array
    {
        $content = trim($content);
        if ($content === '') {
            return [];
        }

        $rows = [];
        $lines = preg_split('/\r\n|\r|\n/', $content);
        if (!is_array($lines)) {
            return [];
        }

        foreach ($lines as $line) {
            if ($line === '') {
                continue;
            }

            $cells = str_getcsv($line, $delimiter);
            if (!is_array($cells)) {
                continue;
            }

            $normalized = array_map(
                static function ($cell): string {
                    return trim((string) $cell);
                },
                $cells
            );

            $hasValue = false;
            foreach ($normalized as $value) {
                if ($value !== '') {
                    $hasValue = true;
                    break;
                }
            }

            if ($hasValue) {
                $rows[] = $normalized;
            }
        }

        return $rows;
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function resolve_delimiter(array $settings): string
    {
        $delimiter = (string) ($settings['csv_delimiter'] ?? ',');
        return in_array($delimiter, [',', ';', "\t"], true) ? $delimiter : ',';
    }

    private function resolve_google_sheet_csv_url(string $url): string
    {
        $url = esc_url_raw($url);
        if ($url === '' || !wp_http_validate_url($url)) {
            return '';
        }

        if (stripos($url, 'output=csv') !== false || stripos($url, 'format=csv') !== false) {
            return $url;
        }

        $matches = [];
        if (!preg_match('~https?://docs\.google\.com/spreadsheets/d/([a-zA-Z0-9\-_]+)~i', $url, $matches)) {
            return $url;
        }

        $sheetId = $matches[1] ?? '';
        if ($sheetId === '') {
            return $url;
        }

        $gid = '';
        $parsed = wp_parse_url($url);
        if (is_array($parsed) && !empty($parsed['query'])) {
            parse_str((string) $parsed['query'], $queryVars);
            if (!empty($queryVars['gid'])) {
                $gid = (string) $queryVars['gid'];
            }
        }

        $csvUrl = 'https://docs.google.com/spreadsheets/d/' . rawurlencode($sheetId) . '/gviz/tq?tqx=out:csv';
        if ($gid !== '') {
            $csvUrl .= '&gid=' . rawurlencode($gid);
        }

        return $csvUrl;
    }

    private function fetch_remote_content(string $url): string
    {
        $url = esc_url_raw($url);
        if ($url === '' || !wp_http_validate_url($url)) {
            return '';
        }

        $cacheKey = 'calio_table_' . md5($url);
        $cached = get_transient($cacheKey);
        if (is_string($cached) && $cached !== '') {
            return $cached;
        }

        $response = wp_safe_remote_get(
            $url,
            [
                'timeout' => 12,
                'redirection' => 3,
            ]
        );

        if (is_wp_error($response)) {
            return '';
        }

        $statusCode = (int) wp_remote_retrieve_response_code($response);
        if ($statusCode < 200 || $statusCode >= 300) {
            return '';
        }

        $body = wp_remote_retrieve_body($response);
        if (!is_string($body) || $body === '') {
            return '';
        }

        set_transient($cacheKey, $body, 10 * MINUTE_IN_SECONDS);

        return $body;
    }

    private function inject_table_class(string $markup): string
    {
        return (string) preg_replace_callback(
            '/<table\b([^>]*)>/i',
            static function (array $matches): string {
                $attributes = $matches[1] ?? '';
                $classes = ['calio-table-element'];

                if (preg_match('/\bclass=(["\'])(.*?)\1/i', $attributes, $classMatch)) {
                    $classes = array_merge(
                        preg_split('/\s+/', trim((string) $classMatch[2])) ?: [],
                        $classes
                    );
                }

                return '<table class="' . esc_attr(implode(' ', array_unique(array_filter($classes)))) . '">';
            },
            $markup
        );
    }

    /**
     * @return array<int, string>
     */
    private function parse_cells(string $value): array
    {
        $parts = explode('|', $value);

        return array_values(
            array_map(
                static function (string $cell): string {
                    return trim($cell);
                },
                $parts
            )
        );
    }

    /**
     * @param array<string, mixed> $settings
     */
    private function is_enabled(array $settings, string $key, bool $default = false): bool
    {
        if (!array_key_exists($key, $settings)) {
            return $default;
        }

        return (string) $settings[$key] === 'yes';
    }

    /**
     * @param array<string, string> $attributes
     */
    private function render_attributes(array $attributes): string
    {
        $compiled = [];
        foreach ($attributes as $name => $value) {
            $compiled[] = sprintf('%s="%s"', esc_attr($name), esc_attr($value));
        }

        return implode(' ', $compiled);
    }

    private function default_custom_table_markup(): string
    {
        return '<table class="calio-table-element"><thead><tr><th>Feature</th><th>Starter</th><th>Business</th><th>Enterprise</th></tr></thead><tbody><tr><td>Projects</td><td>3</td><td>15</td><td>Unlimited</td></tr><tr><td>Team Members</td><td>2</td><td>10</td><td>Unlimited</td></tr><tr><td>Storage</td><td>20 GB</td><td>200 GB</td><td>2 TB</td></tr><tr><td>Priority Support</td><td>No</td><td>Email</td><td>Dedicated</td></tr></tbody></table>';
    }
}
