<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Image_Size;
use \Elementor\Group_Control_Css_Filter;
use \Elementor\Group_Control_Box_Shadow;
use \Elementor\Group_Control_Border;
use \Elementor\Group_Control_Typography;
use \Elementor\Utils;
use Sifency\Traits\Sifency_Image_Style_Controls;
use \Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Core_Text_Style;

class Sifency_Widget_Postmedia extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Image_Style_Controls;
    use Sifency_Core_Text_Style;

    public function get_name() {
        return 'post-media';
    }

    public function get_title() {
        return __( 'Sifency Feature Image', 'sifency-addons' );
    }

    public function get_icon() {
        return 'eicon-featured-image';
    }

    public function get_categories() {
        return [ 'sifency-post-components' ];
    }

    public function get_style_depends() {
	    return [ 'sifency-typo-style' , 'sifency-frontend-style' ];
    }

    protected function register_controls() {
        $this->start_controls_section(
            'image_section',
            [ 'label' => esc_html__('Image', 'sifency-addons') ]
        );
        $this->add_control(
            'img_source',
            [
                'label' => 'Source', 'type' => Controls_Manager::SELECT,
                'options' => [ 'post_thumbnail' => 'Featured Image', 'custom' => 'Custom Image' ],
                'default' => 'post_thumbnail',
            ]
        );
        $this->add_control(
            'image',
            [ 'label' => 'Custom Image', 'type' => Controls_Manager::MEDIA, 'default' => [ 'url' => Utils::get_placeholder_image_src() ], 'condition' => [ 'img_source' => 'custom' ], 'dynamic' => [ 'active' => true ] ]
        );
        $this->add_group_control(
            Group_Control_Image_Size::get_type(),
            [ 'name' => 'image', 'default' => 'large' ]
        );
        $this->add_responsive_control(
            'align',
            [ 'label' => 'Alignment', 'type' => Controls_Manager::CHOOSE, 'options' => [ 'left' => [ 'title' => 'Left', 'icon' => 'eicon-text-align-left' ], 'center' => [ 'title' => 'Center', 'icon' => 'eicon-text-align-center' ], 'right' => [ 'title' => 'Right', 'icon' => 'eicon-text-align-right' ] ], 'selectors' => [ '{{WRAPPER}}' => 'text-align: {{VALUE}};' ] ]
        );
        $this->add_control(
            'caption_source',
            [ 'label' => 'Caption', 'type' => Controls_Manager::SELECT, 'options' => [ 'none' => 'None', 'attachment' => 'Attachment Caption', 'custom' => 'Custom Caption' ], 'default' => 'none' ]
        );
        $this->add_control(
            'caption',
            [ 'label' => 'Custom Caption', 'type' => Controls_Manager::TEXTAREA, 'condition' => [ 'caption_source' => 'custom' ], 'dynamic' => [ 'active' => true ] ]
        );
        $this->add_control(
            'link_to',
            [ 'label' => 'Link', 'type' => Controls_Manager::SELECT, 'default' => 'none', 'options' => [ 'none' => 'None', 'file' => 'Media File (Lightbox)', 'post' => 'Post URL', 'custom' => 'Custom URL' ] ]
        );
        $this->add_control(
            'link',
            [ 'label' => 'Link', 'type' => Controls_Manager::URL, 'dynamic' => [ 'active' => true ], 'condition' => [ 'link_to' => 'custom' ], 'show_label' => false ]
        );
        $this->end_controls_section();
        
        $this->add_sifency_image_style_controls();
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'caption_style',
            'label'    => 'Caption Style',
            'selector' => '.sifency-caption-style',
            'target_children' => false,
        ]);
        $this->add_sifency_animation_controls();
        $this->update_control(
            'sifency_animation_target',
            [
                'type' => Controls_Manager::HIDDEN,
                'default' => 'wrapper',
            ]
        );
    }

        /**
     * Render the widget output on the frontend.
     *
     * @since 1.0.4
     * @access protected
     */
    protected function render() {
        $settings = $this->get_settings_for_display();
        $animation_manager = new Sifency_Animation_Manager($settings);
        $image_id = null;
        $image_html = '';

        if ( 'custom' === $settings['img_source'] ) {
            $image_id = $settings['image']['id'];
        } else {
            $image_id = get_post_thumbnail_id();
        }

        if ( ! empty($image_id) ) {
            $image_html = wp_get_attachment_image( $image_id, $settings['image_size'] );
        } else {
            if ( \Elementor\Plugin::$instance->editor->is_edit_mode() || 'custom' === $settings['img_source'] ) {
                 $image_html = sprintf( '<img src="%s" alt="Placeholder Image" />', esc_url( \Elementor\Utils::get_placeholder_image_src() ) );
            } else {
                return;
            }
        }
        
        $caption_text = '';
        if ( ! empty( $settings['caption_source'] ) && ! empty($image_id) ) {
            if ( 'attachment' === $settings['caption_source'] ) {
                $caption_text = wp_get_attachment_caption( $image_id );
            } elseif ( 'custom' === $settings['caption_source'] ) {
                $caption_text = $settings['caption'];
            }
        } elseif ( \Elementor\Plugin::$instance->editor->is_edit_mode() && ! empty($settings['caption_source']) ) {
            if ('custom' === $settings['caption_source']) {
                 $caption_text = $settings['caption'];
            } else {
                 $caption_text = esc_html__('Image caption placeholder', 'sifency-addons');
            }
        }
        
        $link_url = '';
        if ( 'none' !== $settings['link_to'] ) {
            if ( 'custom' === $settings['link_to'] && ! empty($settings['link']['url']) ) {
                $link_url = $settings['link']['url'];
                $this->add_link_attributes('link', $settings['link']);
            } elseif ( 'file' === $settings['link_to'] ) {
                $image_src = wp_get_attachment_image_src($image_id, 'full');
                if ( $image_src ) {
                    $link_url = $image_src[0];
                    $this->add_render_attribute('link', [ 'href' => $link_url, 'data-elementor-open-lightbox' => 'yes' ]);
                }
            } elseif ( 'post' === $settings['link_to'] ) {
                $link_url = get_permalink();
                $this->add_render_attribute('link', 'href', $link_url);
            }
        }

        $wrapper_attrs_string = $animation_manager->get_wrapper_attributes(['sifency-dynamic-image-wrapper']);
        $this->add_render_attribute('image-wrapper', 'class', 'sifency-dynamic-image sifency-image');
        if ( ! empty( $settings['hover_animation'] ) ) {
            $this->add_render_attribute( 'image-wrapper', 'class', 'elementor-animation-' . $settings['hover_animation'] );
        }
        ?>
        <div <?php echo wp_kses_post ( $wrapper_attrs_string); ?><?php  ?>>
            <figure class="sifency-dynamic-image-figure sifency-image-container">
                <?php if ( $link_url ) : ?>
                    <a <?php echo wp_kses_post ( $this->get_render_attribute_string( 'link' )); ?><?php  ?>>
                <?php endif; ?>

                <div <?php echo wp_kses_post ( $this->get_render_attribute_string( 'image-wrapper' ) ); ?><?php  ?>>
                    <?php echo wp_kses_post( $image_html ); ?>
                    <div class="sifency-image-overlay"></div>
                </div>

                <?php if ( $link_url ) : ?>
                    </a>
                <?php endif; ?>

                <?php if ( ! empty( $caption_text ) ) : ?>
                    <figcaption class="sifency-image-caption sifency-caption-style">
                        <?php echo wp_kses_post( $caption_text ); ?>
                    </figcaption>
                <?php endif; ?>
            </figure>
        </div>
        <?php
    }

    /**
	 * Render the widget output in the editor.
	 *
	 * Written as a Backbone JavaScript template and used to generate the live preview.
	 *
	 * @since 1.0.4
	 * @access protected
	 */
    protected function _content_template() {
        ?>
        <#
        var imageUrl = '<?php echo esc_url( \Elementor\Utils::get_placeholder_image_src() ); ?>';
        if ( 'custom' === settings.img_source && settings.image.url ) {
            imageUrl = settings.image.url;
        }
        var imageHtml = '<img src="' + imageUrl + '" alt="Preview Image" />';

        var captionText = '';
        if ( settings.caption_source ) {
            if ( 'attachment' === settings.caption_source ) {
                // We can't get the real attachment caption, so we show a placeholder.
                captionText = 'Image caption placeholder';
            } else if ( 'custom' === settings.caption_source ) {
                captionText = settings.caption;
            }
        }
        
        var linkUrl = '';
        if ( 'none' !== settings.link_to ) {
            if ( 'custom' === settings.link_to && settings.link.url ) {
                linkUrl = settings.link.url;
                view.addRenderAttribute( 'link', 'href', settings.link.url );
                if ( settings.link.is_external ) {
                    view.addRenderAttribute( 'link', 'target', '_blank' );
                }
                if ( settings.link.nofollow ) {
                    view.addRenderAttribute( 'link', 'rel', 'nofollow' );
                }
            } else if ( 'file' === settings.link_to ) {
                linkUrl = imageUrl; // Link to the image itself for lightbox
                view.addRenderAttribute( 'link', {
                    'href': linkUrl,
                    'data-elementor-open-lightbox': 'yes'
                });
            } else if ( 'post' === settings.link_to ) {
                linkUrl = '#'; // Placeholder link for post
                view.addRenderAttribute( 'link', 'href', '#' );
            }
        }

        view.addRenderAttribute( 'image-wrapper', 'class', 'sifency-dynamic-image sifency-image' );
        if ( settings.hover_animation ) {
            view.addRenderAttribute( 'image-wrapper', 'class', 'elementor-animation-' + settings.hover_animation );
        }
        #>
        <div class="sifency-dynamic-image-wrapper">
            <figure class="sifency-dynamic-image-figure sifency-image-container">
                <# if ( linkUrl ) { #>
                    <a {{{ view.getRenderAttributeString( 'link' ) }}}>
                <# } #>

                <div {{{ view.getRenderAttributeString( 'image-wrapper' ) }}}>
                    {{{ imageHtml }}}
                    <div class="sifency-image-overlay"></div>
                </div>

                <# if ( linkUrl ) { #>
                    </a>
                <# } #>

                <# if ( captionText ) { #>
                    <figcaption class="sifency-image-caption sifency-caption-style">
                        {{{ captionText }}}
                    </figcaption>
                <# } #>
            </figure>
        </div>
        <?php
    }
}