<?php

namespace Lknwp\CrowdfundingExtension\Includes\elementorFields;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Lknwp\CrowdfundingExtension\Includes\elementorFields\helpers\LknwpCrowdfundingListingFunctions;

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

class LknwpCrowdfundingTemplateProductImage extends Widget_Base
{
    private $lknwpHelper;
    private $uniqId;

    public function __construct($data = [], $args = null)
    {
        parent::__construct($data, $args);

        $this->lknwpHelper = new LknwpCrowdfundingListingFunctions();
        $this->uniqId = uniqid();
    }

    public function get_name()
    {
        return 'lkn-wp-crowdfunding-product-image';
    }

    public function get_title()
    {
        return __('Product Image', 'link-nacional-wp-crowdfunding-extension');
    }

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

    public function get_categories()
    {
        return ['lkn-wp-crowdfunding-extension'];
    }

    protected function _register_controls()
    {
        $this->start_controls_section(
            'content_section',
            [
                'label' => __('Content', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        // Controle para imagem alternativa caso o produto não tenha imagem de destaque
        $this->add_control(
            'fallback_image',
            [
                'label' => __('Alternative Image', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::MEDIA,
                'default' => [
                    'url' => '',
                ],
                'description' => __('Image to be displayed if the product does not have a featured image.', 'link-nacional-wp-crowdfunding-extension'),
            ]
        );

        // Controle para selecionar o tamanho da imagem
        $this->add_control(
            'image_size',
            [
                'label' => __('Image Size', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SELECT,
                'default' => 'full',
                'options' => [
                    'small'  => __('Small', 'link-nacional-wp-crowdfunding-extension'),
                    'medium' => __('Medium', 'link-nacional-wp-crowdfunding-extension'),
                    'large'  => __('Large', 'link-nacional-wp-crowdfunding-extension'),
                    'full'   => __('Full', 'link-nacional-wp-crowdfunding-extension'),
                ],
                'description' => __('Select the product image size.', 'link-nacional-wp-crowdfunding-extension'),
            ]
        );

        $this->add_control(
            'show_favorite_button',
            [
                'label' => __('Show Favorite Button', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Enabled', 'link-nacional-wp-crowdfunding-extension'),
                'label_off' => __('Disabled', 'link-nacional-wp-crowdfunding-extension'),
                'return_value' => 'yes',
                'default' => 'yes', // The button will be enabled by default
                'description' => __('Enable or disable the favorite button.', 'link-nacional-wp-crowdfunding-extension'),
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'style_section',
            [
                'label' => __('Style', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        // Altura da imagem com Slider
        $this->add_control(
            'image_height',
            [
                'label' => __('Image Height', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => [ 'px', '%' ],
                'default' => [
                    'size' => 100,
                    'unit' => '%',
                ],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 2000,
                    ],
                    '%' => [
                        'min' => 0,
                        'max' => 100,
                    ],
                ],
                'description' => __('Set the image height.', 'link-nacional-wp-crowdfunding-extension'),
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-image' => 'height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        // Largura da imagem com Slider
        $this->add_control(
            'image_width',
            [
                'label' => __('Image Width', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => [ 'px', '%' ],
                'default' => [
                    'size' => 100,
                    'unit' => '%',
                ],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 2000,
                    ],
                    '%' => [
                        'min' => 0,
                        'max' => 100,
                    ],
                ],
                'description' => __('Set the image width.', 'link-nacional-wp-crowdfunding-extension'),
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-image' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        // Controle de alinhamento horizontal (Justify Content)
        $this->add_control(
            'image_justify',
            [
                'label' => __('Image Justify Content', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'flex-start' => [
                        'title' => __('Left', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-h-align-left',
                    ],
                    'center' => [
                        'title' => __('Center', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-h-align-center',
                    ],
                    'flex-end' => [
                        'title' => __('Right', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-h-align-right',
                    ],
                ],
                'default' => 'center',
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-image-container' => 'justify-content: {{VALUE}};',
                ],
            ]
        );

        // Controle de alinhamento vertical (Align Items)
        $this->add_control(
            'image_align',
            [
                'label' => __('Image Align Items', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'flex-start' => [
                        'title' => __('Top', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-v-align-top',
                    ],
                    'center' => [
                        'title' => __('Middle', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-v-align-middle',
                    ],
                    'flex-end' => [
                        'title' => __('Bottom', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-v-align-bottom',
                    ],
                ],
                'default' => 'center',
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-image-container' => 'align-items: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'lkn_active_color',
            [
                'label' => __('Active Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'default' => '#e52e44',
            ]
        );

        $this->add_control(
            'lkn_active_shadow_color_1',
            [
                'label' => __('Active Shadow Color 1', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'default' => '#fa4654',
            ]
        );

        $this->add_control(
            'lkn_active_shadow_color_2',
            [
                'label' => __('Active Shadow Color 2', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'default' => '#fb626e',
            ]
        );

        $this->add_control(
            'lkn_inactive_color',
            [
                'label' => __('Inactive Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
            ]
        );

        $this->add_control(
            'lkn_background_color',
            [
                'label' => __('Background Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'default' => '#00A859',
            ]
        );

        $this->end_controls_section();
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $edit_mode = false;

        // Recupera a imagem de destaque do produto
        $product_id = get_the_ID();
        $thumbnail_id = get_post_thumbnail_id($product_id);

        // Inicializa a variável para armazenar a imagem
        $thumbnail = '';
        $full_image_url = '';

        if ($thumbnail_id) {
            // Se houver uma imagem de destaque
            $thumbnail = get_the_post_thumbnail($product_id, $settings['image_size']);
            $full_image_url = wp_get_attachment_image_url($thumbnail_id, 'full'); // URL da imagem em tamanho completo
        } else {
            // Se não houver imagem de destaque, utiliza a imagem padrão do WooCommerce
            $placeholder_id = get_option('woocommerce_placeholder_image');
            $thumbnail = wp_get_attachment_image($placeholder_id, $settings['image_size']);
            $full_image_url = wp_get_attachment_image_url($placeholder_id, 'full');
        }

        if (\Elementor\Plugin::$instance->editor->is_edit_mode() || is_preview()) {
            $edit_mode = true;
            // Se não houver imagem de destaque ou placeholder, verifica a imagem alternativa do controle
            if (!empty($settings['fallback_image']['url'])) {
                $thumbnail = wp_get_attachment_image($settings['fallback_image']['id'], $settings['image_size']);
                $full_image_url = wp_get_attachment_image_url($settings['fallback_image']['id'], 'full');
            }
        }

        // Verifica se a imagem existe e aplica a classe personalizada
        if ($thumbnail) {
            // Adiciona a classe "lkn-product-image" à imagem
            $thumbnail = str_replace('class="', 'class="lkn-product-image ', $thumbnail);

            // Exibe o contêiner principal com display flex
            echo '<div class="lkn-product-image-container" style="display: flex; position: relative;" data-product-id="' . esc_attr($product_id) . '">';

            // Exibe o wrapper da imagem com flex
            echo '<div class="lkn-image-wrapper" style="display: flex; align-items: center; justify-content: center; position: relative;">';

            // Exibe o link da imagem para zoom
            echo '<a href="' . esc_url($full_image_url) . '" class="lkn-zoom" data-zoom-image="' . esc_url($full_image_url) . '">';
            echo wp_kses_post($thumbnail);
            echo '</a>';

            // Lógica de favoritar
            $user_id = get_current_user_id();
            $author_id = get_post_field('post_author', $product_id);
            $loved_campaign_ids = get_user_meta($user_id, 'loved_campaign_ids', true);
            $loved_campaign_ids = !empty($loved_campaign_ids) ? json_decode($loved_campaign_ids, true) : [];
            $is_favorited = in_array($product_id, $loved_campaign_ids);

            // Define as cores do SVG com base no estado
            $cls_2_fill = $is_favorited ? $settings['lkn_active_color'] : $settings['lkn_inactive_color'];
            $cls_3_fill = $is_favorited ? $settings['lkn_active_shadow_color_1'] : $settings['lkn_inactive_color'];
            $cls_4_fill = $is_favorited ? $settings['lkn_active_shadow_color_2'] : $settings['lkn_inactive_color'];

            // Gera o valor para o input hidden
            $colors_value = implode(',', [
                $settings['lkn_active_color'],
                $settings['lkn_active_shadow_color_1'],
                $settings['lkn_active_shadow_color_2'],
                $settings['lkn_inactive_color']
            ]);

            if ('yes' === $settings['show_favorite_button']) {
                if (get_post_type() === 'product' || \Elementor\Plugin::$instance->editor->is_edit_mode() || is_preview()) {
                    if ($user_id) {
                        // Exibe o botão de favoritar
                        echo '<div class="lkn-btn-container">';
                        echo '<input type="hidden" class="lkn-edit-mode" name="lkn-edit-mode" value="' . ($edit_mode ? 'active' : 'inactive') . '">';
                        echo '<input type="hidden" class="lkn-edit-mode" name="lkn-user-id" value="' . esc_attr($user_id) . '">';
                        echo '<input type="hidden" class="lkn-edit-mode" name="lkn-user-product-id" value="' . esc_attr($author_id) . '">';
                        echo '<input type="hidden" class="lkn-heart-status" name="lkn-heart-status" value="' . ($is_favorited ? 'active' : 'inactive') . '">';
                        echo '<input type="hidden" class="lkn-heart-colors" name="lkn-heart-colors" value="' . esc_attr($colors_value) . '">';
                        echo '<button class="lkn-heart-btn" data-product-id="' . esc_attr($product_id) . '" data-user-id="' . esc_attr($user_id) . '">
                            <svg class="lkn-heart" data-name="50" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
                                <title>Heart icon</title>
                                <circle class="cls-1 cls-1-' . esc_attr($this->uniqId) . '" cx="256" cy="256" r="256" fill="' . esc_attr($settings['lkn_background_color']) . '"/>
                                <path class="cls-2 cls-2-' . esc_attr($this->uniqId) . '" d="M409.05,283.21,273.89,418.36a25.28,25.28,0,0,1-35.78,0L126,306.21l-23-23A92,92,0,1,1,233,153.15l23,23,23-23A92,92,0,0,1,409.05,283.21Z" fill="' . esc_attr($cls_2_fill) . '"/>
                                <path class="cls-3 cls-3-' . esc_attr($this->uniqId) . '" d="M409.05,283.21,299.56,392.7a25.29,25.29,0,0,1-35.79,0L151.61,280.54l-23-23a92,92,0,0,1-11.56-116,92,92,0,0,1,116,11.57l23,23,23-23A92,92,0,0,1,409.05,283.21Z" fill="' . esc_attr($cls_3_fill) . '"/>
                                <ellipse class="cls-4 cls-4-' . esc_attr($this->uniqId) . '" cx="373.08" cy="169.49" rx="23.33" ry="38.57" transform="translate(14.73 368.23) rotate(-53.45)" fill="' . esc_attr($cls_4_fill) . '"/>
                                <ellipse class="cls-4 cls-4-' . esc_attr($this->uniqId) . '" cx="409.8" cy="225.81" rx="14.74" ry="24.37" transform="translate(-28.72 62.63) rotate(-8.45)" fill="' . esc_attr($cls_4_fill) . '"/>
                            </svg>
                        </button>';
                        echo '</div>';
                    }
                }
            }

            // Finaliza a estrutura do contêiner
            echo '</div>'; // Fecha o lkn-image-wrapper
            echo '</div>'; // Fecha o lkn-product-image-container
        }
    }
}
