<?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\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Css_Filter;
use Softech_Addons_for_Elementor\Includes\SITS_Single_Post_Widget_Base;

class sitsel_post_thumbnail extends SITS_Single_Post_Widget_Base {

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

    public function get_name() { return 'sitsel_post_thumbnail'; }
    public function get_title() { return __( 'SITS Post Thumbnail', 'softech-addons-for-elementor' ); }
    public function get_icon() { return 'eicon-featured-image'; }
    public function get_keywords() { return [ 'post', 'image', 'thumbnail', 'featured', 'single' ]; }

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

        $this->add_control( 'image_size', [
            'label'   => esc_html__( 'Image Size', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'large',
            'options' => [ 'thumbnail' => 'Thumbnail', 'medium' => 'Medium', 'large' => 'Large', 'full' => 'Full', 'custom' => 'Custom' ],
        ] );

        $this->add_responsive_control( 'custom_width', [
            'label' => esc_html__( 'Custom Width', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', '%' ],
            'range' => [ 'px' => [ 'min' => 40, 'max' => 1200 ], '%' => [ 'min' => 10, 'max' => 100 ] ],
            'default' => [ 'size' => 800, 'unit' => 'px' ],
            'condition' => [ 'image_size' => 'custom' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-frame' => 'width: {{SIZE}}{{UNIT}};' ],
        ] );

        $this->add_responsive_control( 'custom_height', [
            'label' => esc_html__( 'Custom Height', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', 'vh' ],
            'range' => [ 'px' => [ 'min' => 40, 'max' => 1200 ], 'vh' => [ 'min' => 10, 'max' => 100 ] ],
            'default' => [ 'size' => 100, 'unit' => 'px' ],
            'condition' => [ 'image_size' => 'custom' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-frame' => 'height: {{SIZE}}{{UNIT}};' ],
        ] );

        $this->add_control( 'alignment', [
            'label' => esc_html__( 'Alignment', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::CHOOSE,
            'default' => 'center',
            'options' => [
                'flex-start' => [ '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' ],
                'flex-end' => [ 'title' => esc_html__( 'Right', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-right' ],
            ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-wrapper' => 'align-items: {{VALUE}};' ],
        ] );

        $this->add_control( 'link_to', [
            'label' => esc_html__( 'Link To', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SELECT,
            'default' => 'none',
            'options' => [ 'none' => esc_html__( 'None', 'softech-addons-for-elementor' ), 'post' => esc_html__( 'Post URL', 'softech-addons-for-elementor' ), 'custom' => esc_html__( 'Custom URL', 'softech-addons-for-elementor' ), 'lightbox' => esc_html__( 'Lightbox', 'softech-addons-for-elementor' ) ],
        ] );

        $this->add_control( 'custom_link', [
            'label' => esc_html__( 'Custom URL', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::URL,
            'condition' => [ 'link_to' => 'custom' ],
        ] );

        $this->add_control( 'alt_text', [
            'label' => esc_html__( 'Alt Text Override', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::TEXT,
            'placeholder' => esc_html__( 'Leave empty to use attachment alt text', 'softech-addons-for-elementor' ),
        ] );

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

        $this->add_control( 'enable_hover_zoom', [
            'label' => esc_html__( 'Hover Zoom', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SWITCHER,
            'default' => 'yes',
        ] );

        $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_responsive_control( 'thumb_width', [
            'label' => esc_html__( 'Width', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', '%' ],
            'range' => [ 'px' => [ 'min' => 100, 'max' => 1600 ], '%' => [ 'min' => 10, 'max' => 100 ] ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-frame' => 'width: {{SIZE}}{{UNIT}};' ],
        ] );
        $this->add_responsive_control( 'thumb_height', [
            'label' => esc_html__( 'Height', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px', 'vh' ],
            'range' => [ 'px' => [ 'min' => 80, 'max' => 1600 ], 'vh' => [ 'min' => 10, 'max' => 100 ] ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-thumbnail-frame' => 'height: {{SIZE}}{{UNIT}};',
                '{{WRAPPER}} .sitsel-post-thumbnail-image' => 'height: 100%;',
            ],
        ] );
        $this->add_control( 'object_fit', [
            'label' => esc_html__( 'Object Fit', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SELECT,
            'default' => 'none',
            'options' => [ 'none' => 'None', 'cover' => 'Cover', 'contain' => 'Contain', 'fill' => 'Fill' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-image' => 'object-fit: {{VALUE}};' ],
            'condition' => [
                'thumb_height[size]!' => '',
                'custom_height[size]!' => '',
            ],
        ] );
        $this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'thumb_border', 'selector' => '{{WRAPPER}} .sitsel-post-thumbnail-frame' ] );
        $this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'thumb_shadow', 'selector' => '{{WRAPPER}} .sitsel-post-thumbnail-frame' ] );
        $this->add_group_control( Group_Control_Css_Filter::get_type(), [ 'name' => 'thumb_filters', 'selector' => '{{WRAPPER}} .sitsel-post-thumbnail-image' ] );
        $this->add_responsive_control( 'thumb_radius', [
            'label' => esc_html__( 'Border Radius', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', '%', 'em' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-frame' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ],
        ] );
        $this->add_responsive_control( 'thumb_gap', [
            'label' => esc_html__( 'Caption Gap', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::SLIDER,
            'size_units' => [ 'px' ],
            'range' => [ 'px' => [ 'min' => 0, 'max' => 40 ] ],
            'default' => [ 'size' => 10, 'unit' => 'px' ],
            'selectors' => [ '{{WRAPPER}} .sitsel-post-thumbnail-caption' => 'margin-top: {{SIZE}}{{UNIT}};' ],
        ] );
        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        $data     = $this->get_featured_image_data( $settings['image_size'] ?? 'large' );
        $post_id  = $this->get_render_post_id();
        $alt      = '' !== trim( (string) ( $settings['alt_text'] ?? '' ) ) ? (string) $settings['alt_text'] : (string) $data['alt'];
        $caption  = isset( $data['caption'] ) ? (string) $data['caption'] : '';
        $hover_zoom = 'yes' === ( $settings['enable_hover_zoom'] ?? 'yes' );

        if ( 'custom' === ( $settings['image_size'] ?? 'large' ) ) {
            $width  = absint( $settings['custom_width']['size'] ?? 800 );
            $height = absint( $settings['custom_height']['size'] ?? 100 );
            if ( $data['id'] ) {
                $src = wp_get_attachment_image_src( $data['id'], [ $width, $height ] );
                if ( is_array( $src ) && ! empty( $src[0] ) ) {
                    $data['url'] = esc_url_raw( $src[0] );
                }
            }
        }

        $aspect_ratio = $this->get_thumbnail_aspect_ratio( $settings, $data );
        $frame_style   = $this->get_thumbnail_frame_style( $settings, $data, $aspect_ratio );

        $link_href = '';
        if ( 'post' === ( $settings['link_to'] ?? 'none' ) && $post_id ) {
            $link_href = get_permalink( $post_id );
        } elseif ( 'custom' === ( $settings['link_to'] ?? 'none' ) && ! empty( $settings['custom_link']['url'] ) ) {
            $link_href = $settings['custom_link']['url'];
        } elseif ( 'lightbox' === ( $settings['link_to'] ?? 'none' ) ) {
            $link_href = $data['url'];
        }

        $this->add_render_attribute( 'wrapper', [ 'class' => 'sitsel-post-thumbnail-wrapper' ] );
        if ( $hover_zoom ) {
            $this->add_render_attribute( 'wrapper', [ 'class' => 'has-hover-zoom' ] );
        }
        $frame_attrs = [ 'class' => 'sitsel-post-thumbnail-frame' ];
        if ( '' !== $frame_style ) {
            $frame_attrs['style'] = $frame_style;
        }
        $this->add_render_attribute( 'frame', $frame_attrs );

        if ( 'custom' === ( $settings['link_to'] ?? 'none' ) && ! empty( $settings['custom_link']['is_external'] ) ) {
            $this->add_render_attribute( 'link', [ 'target' => '_blank', 'rel' => 'noopener noreferrer' ] );
        }

        if ( 'lightbox' === ( $settings['link_to'] ?? 'none' ) ) {
            $this->add_render_attribute( 'link', [
                'data-elementor-open-lightbox' => 'yes',
                'data-elementor-lightbox-slideshow' => 'sitsel-post-thumbnail',
            ] );
        }

        echo '<figure ' . $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( 'frame' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.

        if ( '' !== $link_href ) {
            echo '<a class="sitsel-post-thumbnail-link" href="' . esc_url( $link_href ) . '" ' . $this->get_render_attribute_string( 'link' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.
        }

        if ( ! empty( $data['id'] ) ) {
            $render_size = $settings['image_size'] ?? 'large';
            if ( 'custom' === $render_size ) {
                $render_size = [
                    absint( $settings['custom_width']['size'] ?? 800 ),
                    absint( $settings['custom_height']['size'] ?? 100 ),
                ];
            }

            $image_attrs = [
                'class'        => 'sitsel-post-thumbnail-image',
                'alt'          => $alt,
                'loading'      => 'eager',
                'fetchpriority'=> 'high',
                'decoding'     => 'async',
                'style'        => 'display:block;width:100%;height:100%;max-width:100%;object-position:center center;',
            ];

            echo wp_kses_post( wp_get_attachment_image( (int) $data['id'], $render_size, false, $image_attrs ) );
        } else {
            // Show dummy placeholder image from assets
            $placeholder_url = plugins_url( 'assets/images/placeholder-image.webp', dirname( dirname( __FILE__ ) ) . '/softech-addons-for-elementor.php' );
            echo '<img src="' . esc_url( $placeholder_url ) . '" class="sitsel-post-thumbnail-image sitsel-post-thumbnail-placeholder-img" alt="Placeholder" style="display:block;width:100%;height:100%;max-width:100%;object-fit:none;object-position:center center;" />';
        }

        if ( '' !== $link_href ) {
            echo '</a>';
        }

        echo '</div>';

        if ( 'yes' === ( $settings['show_caption'] ?? '' ) && '' !== $caption ) {
            echo '<figcaption class="sitsel-post-thumbnail-caption">' . esc_html( $caption ) . '</figcaption>';
        }

        echo '</figure>';
    }

    private function get_thumbnail_aspect_ratio( array $settings, array $data ): string {
        $size = $settings['image_size'] ?? 'large';

        if ( 'custom' === $size ) {
            $width_control  = $settings['custom_width'] ?? [];
            $height_control = $settings['custom_height'] ?? [];
            $width_unit     = strtolower( (string) ( $width_control['unit'] ?? '' ) );
            $height_unit    = strtolower( (string) ( $height_control['unit'] ?? '' ) );
            $width_value    = absint( $width_control['size'] ?? 0 );
            $height_value   = absint( $height_control['size'] ?? 0 );

            if ( $width_value && $height_value && 'px' === $width_unit && 'px' === $height_unit ) {
                return $width_value . ' / ' . $height_value;
            }

            return '';
        }

        $width  = absint( $data['width'] ?? 0 );
        $height = absint( $data['height'] ?? 0 );

        if ( $width && $height ) {
            return $width . ' / ' . $height;
        }

        return '';
    }

    private function get_thumbnail_frame_style( array $settings, array $data, string $aspect_ratio ): string {
        $styles = [ 'display:block', 'width:100%' ];
        $size   = $settings['image_size'] ?? 'large';

        if ( 'custom' === $size ) {
            $width  = $this->format_dimension_value( $settings['custom_width'] ?? [], '800px' );
            $height = $this->format_dimension_value( $settings['custom_height'] ?? [], '100px' );
        } else {
            $width  = $this->resolve_thumbnail_dimension( $settings['thumb_width'] ?? [], $this->get_image_dimension_fallback( $data, 'width', '100%' ), '100', '%' );
            $height = $this->resolve_thumbnail_dimension( $settings['thumb_height'] ?? [], $this->get_image_dimension_fallback( $data, 'height', '100px' ), '100', 'px' );
        }

        
        if ( '' !== $width ) {
            $styles[] = 'width:' . $width;
        }

        if ( '' !== $height ) {
            $styles[] = 'height:' . $height;
        }

        if ( '' !== $aspect_ratio ) {
            $styles[] = '--sitsel-post-thumbnail-aspect-ratio:' . $aspect_ratio;
            $styles[] = 'aspect-ratio:var(--sitsel-post-thumbnail-aspect-ratio)';
        }

        return implode( ';', $styles ) . ';';
    }

    private function resolve_thumbnail_dimension( array $control, string $fallback, string $legacy_default_size = '', string $legacy_default_unit = '' ): string {
        $size = $control['size'] ?? '';
        $unit = strtolower( (string) ( $control['unit'] ?? '' ) );

        if ( '' === $size || null === $size ) {
            return $fallback;
        }

        if ( '' !== $legacy_default_size && '' !== $legacy_default_unit && (string) $size === $legacy_default_size && $legacy_default_unit === $unit ) {
            return $fallback;
        }

        return $this->format_dimension_value( $control, $fallback );
    }

    private function get_image_dimension_fallback( array $data, string $dimension, string $legacy_fallback ): string {
        $value = absint( $data[ $dimension ] ?? 0 );
        if ( $value > 0 ) {
            return $value . 'px';
        }

        return $legacy_fallback;
    }

    private function format_dimension_value( array $control, string $fallback ): string {
        $size = $control['size'] ?? '';
        $unit = strtolower( (string) ( $control['unit'] ?? '' ) );

        if ( '' === $size || null === $size ) {
            return $fallback;
        }

        if ( is_numeric( $size ) ) {
            $size = (string) $size;
        } else {
            $size = trim( (string) $size );
        }

        if ( '' === $size ) {
            return $fallback;
        }

        if ( '' === $unit ) {
            return $size;
        }

        return $size . $unit;
    }
}
