<?php
namespace Softech_Addons_for_Elementor\Widgets;

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

if ( ! class_exists( '\\Softech_Addons_for_Elementor\\Includes\\SITS_Single_Post_Widget_Base' ) ) {
    require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-single-post-widget-base.php';
}

use Elementor\Controls_Manager;
use Elementor\Icons_Manager;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Softech_Addons_for_Elementor\Includes\SITS_Single_Post_Widget_Base;

class sitsel_post_content extends SITS_Single_Post_Widget_Base {

    protected function get_style_handle(): string { return 'sitsel-post-content-css'; }
    protected function get_style_file(): string { return 'assets/css/sitsel-post-content.css'; }
    protected function get_script_handle(): string { return 'sitsel-post-content-js'; }
    protected function get_script_file(): string { return 'assets/js/sitsel-post-content.js'; }

    public function get_name() { return 'sitsel_post_content'; }
    public function get_title() { return __( 'SITS Post Content', 'softech-addons-for-elementor' ); }
    public function get_icon() { return 'eicon-text'; }
    public function get_keywords() { return [ 'post', 'content', 'excerpt', 'article', 'single' ]; }

    protected function _register_controls() {
        $this->start_controls_section( 'section_content', [ 'label' => esc_html__( 'Content', 'softech-addons-for-elementor' ) ] );

        $this->add_control( 'mode', [
            'label'   => esc_html__( 'Display Mode', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'full',
            'options' => [ 'full' => esc_html__( 'Full Content', 'softech-addons-for-elementor' ), 'excerpt' => esc_html__( 'Excerpt', 'softech-addons-for-elementor' ) ],
        ] );

        $this->add_responsive_control( 'excerpt_length', [
            'label' => esc_html__( 'Excerpt Length', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::NUMBER,
            'default' => 40,
            'tablet_default' => 30,
            'mobile_default' => 20,
            'min' => 5,
            'max' => 200,
            'condition' => [ 'mode' => 'excerpt' ],
        ] );

        $this->add_control( 'show_read_more', [
            'label' => esc_html__( 'Show Read More Button', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SWITCHER,
            'default' => '',
            'condition' => [ 'mode' => 'excerpt' ],
        ] );

        $this->add_control( 'read_more_text', [
            'label' => esc_html__( 'Read More Text', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__( 'Read More', 'softech-addons-for-elementor' ),
            'condition' => [ 'mode' => 'excerpt', 'show_read_more' => 'yes' ],
        ] );

        $this->add_control( 'read_more_icon', [
            'label' => esc_html__( 'Icon', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::ICONS,
            'condition' => [ 'mode' => 'excerpt', 'show_read_more' => 'yes' ],
        ] );

        $this->add_control( 'read_more_icon_position', [
            'label' => esc_html__( 'Icon Position', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::CHOOSE,
            'default' => 'left',
            'options' => [
                'left' => [ 'title' => esc_html__( 'Left', 'softech-addons-for-elementor' ), 'icon' => 'eicon-h-align-left' ],
                'right' => [ 'title' => esc_html__( 'Right', 'softech-addons-for-elementor' ), 'icon' => 'eicon-h-align-right' ],
            ],
            'toggle' => false,
            'condition' => [
                'mode' => 'excerpt',
                'show_read_more' => 'yes',
                'read_more_icon[value]!' => '',
            ],
        ] );

        $this->add_control( 'read_more_alignment', [
            'label' => esc_html__( 'Button Alignment', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::CHOOSE,
            'default' => 'left',
            'options' => [
                'left' => [ 'title' => esc_html__( 'Left', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-left' ],
                'center' => [ 'title' => esc_html__( 'Center', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-center' ],
                'right' => [ 'title' => esc_html__( 'Right', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-right' ],
            ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-content-read-more-wrap' => 'text-align: {{VALUE}};',
            ],
            'condition' => [ 'mode' => 'excerpt', 'show_read_more' => 'yes' ],
        ] );

        $this->add_control( 'show_toc', [
            'label' => esc_html__( 'Enable Table of Contents', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SWITCHER,
            'default' => '',
        ] );

        $this->add_control( 'toc_title', [
            'label' => esc_html__( 'TOC Title', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__( 'Table of Contents', 'softech-addons-for-elementor' ),
            'condition' => [ 'show_toc' => 'yes' ],
        ] );

        $this->add_control( 'drop_cap', [
            'label' => esc_html__( 'Drop Cap', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SWITCHER,
            'default' => '',
        ] );

        $this->add_control( 'alignment', [
            'label' => esc_html__( 'Alignment', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::CHOOSE,
            'default' => 'left',
            'options' => [
                'left' => [ 'title' => esc_html__( 'Left', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-left' ],
                'center' => [ 'title' => esc_html__( 'Center', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-center' ],
                'right' => [ 'title' => esc_html__( 'Right', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-right' ],
                'justify' => [ 'title' => esc_html__( 'Justify', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-justify' ],
            ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body' => 'text-align: {{VALUE}};' ],
        ] );

        $this->add_responsive_control( 'content_width', [
            'label' => esc_html__( 'Content Width', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', '%' ],
            'range' => [ 'px' => [ 'min' => 300, 'max' => 1400 ], '%' => [ 'min' => 20, 'max' => 100 ] ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body' => 'max-width: {{SIZE}}{{UNIT}};' ],
        ] );

        $this->add_control( 'columns', [
            'label' => esc_html__( 'Text Columns', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SELECT,
            'default' => '1',
            'options' => [ '1' => '1', '2' => '2', '3' => '3' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body' => 'column-count: {{VALUE}};' ],
        ] );

        $this->add_responsive_control( 'column_gap', [
            'label' => esc_html__( 'Column Gap', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px' ],
            'range' => [ 'px' => [ 'min' => 10, 'max' => 80 ] ],
            'default' => [ 'size' => 24, 'unit' => 'px' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body' => 'column-gap: {{SIZE}}{{UNIT}};' ],
        ] );

        $this->end_controls_section();

        $this->start_controls_section( 'section_style', [ 'label' => esc_html__( 'Style', 'softech-addons-for-elementor' ), 'tab' => Controls_Manager::TAB_STYLE ] );
        $this->add_control( 'text_color', [
            'label' => esc_html__( 'Text Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'default' => '#374151',
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body' => 'color: {{VALUE}};' ],
        ] );
        $this->add_control( 'link_color', [
            'label' => esc_html__( 'Link Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body a' => 'color: {{VALUE}};' ],
        ] );
        $this->add_control( 'link_hover_color', [
            'label' => esc_html__( 'Link Hover Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-body a:hover, {{WRAPPER}} .sitsel-post-content-body a:focus-visible' => 'color: {{VALUE}};' ],
        ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'body_typography', 'selector' => '{{WRAPPER}} .sitsel-post-content-body' ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'heading_typography', 'selector' => '{{WRAPPER}} .sitsel-post-content-body h1, {{WRAPPER}} .sitsel-post-content-body h2, {{WRAPPER}} .sitsel-post-content-body h3, {{WRAPPER}} .sitsel-post-content-body h4, {{WRAPPER}} .sitsel-post-content-body h5, {{WRAPPER}} .sitsel-post-content-body h6' ] );
        $this->add_group_control( Group_Control_Background::get_type(), [ 'name' => 'content_background', 'types' => [ 'classic', 'gradient' ], 'selector' => '{{WRAPPER}} .sitsel-post-content-box' ] );
        $this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'content_border', 'selector' => '{{WRAPPER}} .sitsel-post-content-box' ] );
        $this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'content_shadow', 'selector' => '{{WRAPPER}} .sitsel-post-content-box' ] );
        $this->add_responsive_control( 'content_border_radius', [
            'label' => esc_html__( 'Border Radius', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', '%', 'em', 'rem' ],
            'default' => [ 'top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0, 'unit' => 'px', 'isLinked' => true ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-box' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ],
        ] );
        $this->add_responsive_control( 'content_padding', [
            'label' => esc_html__( 'Padding', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', 'rem' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-content-box' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ],
        ] );
        $this->end_controls_section();

        $this->start_controls_section( 'section_button_style', [ 'label' => esc_html__( 'Read More Button', 'softech-addons-for-elementor' ), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => [ 'mode' => 'excerpt', 'show_read_more' => 'yes' ] ] );
        $this->add_control( 'button_text_color', [ 'label' => esc_html__( 'Text Color', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more' => 'color: {{VALUE}};' ] ] );
        $this->add_control( 'button_bg_color', [ 'label' => esc_html__( 'Background', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'default' => '#111827', 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more' => 'background-color: {{VALUE}};' ] ] );
        $this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'button_border', 'selector' => '{{WRAPPER}} .sitsel-post-content-read-more' ] );
        $this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'button_shadow', 'selector' => '{{WRAPPER}} .sitsel-post-content-read-more' ] );
        $this->add_control( 'button_icon_color', [ 'label' => esc_html__( 'Icon Color', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more .sitsel-post-content-read-more-icon' => 'color: {{VALUE}}; fill: {{VALUE}};' ] ] );
        $this->add_control( 'button_icon_hover_color', [ 'label' => esc_html__( 'Icon Hover Color', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more:hover .sitsel-post-content-read-more-icon, {{WRAPPER}} .sitsel-post-content-read-more:focus-visible .sitsel-post-content-read-more-icon' => 'color: {{VALUE}}; fill: {{VALUE}};' ] ] );
        $this->add_responsive_control( 'button_icon_size', [ 'label' => esc_html__( 'Icon Size', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em', 'rem' ], 'range' => [ 'px' => [ 'min' => 8, 'max' => 40 ], 'em' => [ 'min' => 0.5, 'max' => 3 ], 'rem' => [ 'min' => 0.5, 'max' => 3 ] ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more .sitsel-post-content-read-more-icon' => 'font-size: {{SIZE}}{{UNIT}}; width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};' ] ] );
        $this->add_responsive_control( 'button_icon_spacing', [ 'label' => esc_html__( 'Icon Spacing', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em', 'rem' ], 'range' => [ 'px' => [ 'min' => 0, 'max' => 30 ], 'em' => [ 'min' => 0, 'max' => 3 ], 'rem' => [ 'min' => 0, 'max' => 3 ] ], 'default' => [ 'size' => 8, 'unit' => 'px' ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more.icon-left .sitsel-post-content-read-more-icon' => 'margin-right: {{SIZE}}{{UNIT}};', '{{WRAPPER}} .sitsel-post-content-read-more.icon-right .sitsel-post-content-read-more-icon' => 'margin-left: {{SIZE}}{{UNIT}};' ] ] );
        $this->add_responsive_control( 'button_padding', [ 'label' => esc_html__( 'Padding', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', 'em', 'rem' ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-content-read-more' => 'display: inline-flex; align-items: center; justify-content: center; padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ] );
        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        $post_id  = $this->get_render_post_id();
        $mode     = $settings['mode'] ?? 'full';
        $excerpt_lengths = $this->get_excerpt_lengths( $settings );
        $excerpt_source  = $this->get_excerpt_source_text();
        $content         = 'excerpt' === $mode ? $this->format_excerpt_content( $excerpt_source, $excerpt_lengths['desktop'] ) : $this->get_current_post_content_html();
        $read_more_text = $settings['read_more_text'] ?? esc_html__( 'Read More', 'softech-addons-for-elementor' );
        $read_more_icon = $settings['read_more_icon'] ?? [];
        $read_more_icon_position = $settings['read_more_icon_position'] ?? 'left';

        $this->add_render_attribute( 'wrapper', [ 'class' => 'sitsel-post-content-wrapper', 'itemscope' => 'itemscope', 'itemtype' => 'https://schema.org/BlogPosting' ] );
        $this->add_render_attribute( 'box', [ 'class' => 'sitsel-post-content-box' ] );
        $this->add_render_attribute( 'body', [
            'class' => 'sitsel-post-content-body',
            'data-sitsel-post-content-mode' => $mode,
        ] );

        if ( 'yes' === ( $settings['drop_cap'] ?? '' ) ) {
            $this->add_render_attribute( 'body', [ 'class' => 'has-drop-cap' ] );
        }

        if ( 'yes' === ( $settings['show_toc'] ?? '' ) ) {
            $this->add_render_attribute( 'body', [ 'data-enable-toc' => 'yes', 'data-toc-title' => $settings['toc_title'] ?? esc_html__( 'Table of Contents', 'softech-addons-for-elementor' ) ] );
        }

        if ( 'excerpt' === $mode ) {
            $this->add_render_attribute( 'body', [
                'data-sitsel-excerpt-source' => $excerpt_source,
                'data-sitsel-excerpt-length-desktop' => $excerpt_lengths['desktop'],
                'data-sitsel-excerpt-length-tablet' => $excerpt_lengths['tablet'],
                'data-sitsel-excerpt-length-mobile' => $excerpt_lengths['mobile'],
            ] );
        }

        echo '<div ' . $this->get_render_attribute_string( 'wrapper' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.
        echo '<div ' . $this->get_render_attribute_string( 'box' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.
        if ( 'yes' === ( $settings['show_toc'] ?? '' ) ) {
            echo '<nav class="sitsel-post-content-toc" aria-label="' . esc_attr__( 'Table of contents', 'softech-addons-for-elementor' ) . '"><div class="sitsel-post-content-toc-title">' . esc_html( $settings['toc_title'] ?? esc_html__( 'Table of Contents', 'softech-addons-for-elementor' ) ) . '</div><div class="sitsel-post-content-toc-list"></div></nav>';
        }
        echo '<div ' . $this->get_render_attribute_string( 'body' ) . '>' . wp_kses_post( $content ) . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.

        if ( 'excerpt' === $mode && 'yes' === ( $settings['show_read_more'] ?? '' ) && $post_id ) {
            $button_classes = [ 'sitsel-post-content-read-more', 'icon-' . ( 'right' === $read_more_icon_position ? 'right' : 'left' ) ];

            echo '<div class="sitsel-post-content-read-more-wrap"><a class="' . esc_attr( implode( ' ', $button_classes ) ) . '" href="' . esc_url( get_permalink( $post_id ) ) . '">';

            if ( ! empty( $read_more_icon['value'] ) && 'right' !== $read_more_icon_position ) {
                echo '<span class="sitsel-post-content-read-more-icon sitsel-post-content-read-more-icon-left" aria-hidden="true">';
                Icons_Manager::render_icon( $read_more_icon, [ 'aria-hidden' => 'true' ] );
                echo '</span>';
            }

            echo '<span class="sitsel-post-content-read-more-text">' . esc_html( $read_more_text ) . '</span>';

            if ( ! empty( $read_more_icon['value'] ) && 'right' === $read_more_icon_position ) {
                echo '<span class="sitsel-post-content-read-more-icon sitsel-post-content-read-more-icon-right" aria-hidden="true">';
                Icons_Manager::render_icon( $read_more_icon, [ 'aria-hidden' => 'true' ] );
                echo '</span>';
            }

            echo '</a></div>';
        }

        echo '</div></div>';
    }

    private function get_excerpt_lengths( array $settings ): array {
        $desktop = $this->normalize_excerpt_length_value( $settings['excerpt_length'] ?? 40, 40 );
        $tablet  = $this->normalize_excerpt_length_value( $settings['excerpt_length_tablet'] ?? $desktop, $desktop );
        $mobile  = $this->normalize_excerpt_length_value( $settings['excerpt_length_mobile'] ?? $tablet, $tablet );

        return [
            'desktop' => $desktop,
            'tablet'  => $tablet,
            'mobile'  => $mobile,
        ];
    }

    private function normalize_excerpt_length_value( $value, int $fallback ): int {
        if ( is_array( $value ) ) {
            $value = $value['size'] ?? $value['value'] ?? $fallback;
        }

        $value = absint( $value );
        if ( $value < 5 ) {
            $value = 5;
        }

        return $value > 0 ? $value : max( 5, $fallback );
    }

    private function get_excerpt_source_text(): string {
        $post_id = $this->get_render_post_id();

        if ( ! $post_id ) {
            return trim( wp_strip_all_tags( $this->get_sample_post_excerpt() ) );
        }

        $excerpt = trim( (string) get_the_excerpt( $post_id ) );
        if ( '' !== $excerpt ) {
            $excerpt = wp_strip_all_tags( strip_shortcodes( html_entity_decode( $excerpt, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) );
            return trim( preg_replace( '/\s+/', ' ', $excerpt ) );
        }

        $content = (string) get_post_field( 'post_content', $post_id );
        $content = wp_strip_all_tags( strip_shortcodes( html_entity_decode( $content, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) );
        $content = trim( preg_replace( '/\s+/', ' ', $content ) );

        return '' !== $content ? $content : trim( wp_strip_all_tags( $this->get_sample_post_excerpt() ) );
    }

    private function format_excerpt_content( string $source, int $length ): string {
        $trimmed = wp_trim_words( trim( $source ), max( 5, $length ), '...' );

        return wpautop( esc_html( $trimmed ) );
    }
}
