<?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 LknwpCrowdfundingTemplateProductGallery extends Widget_Base
{
    public function __construct($data = [], $args = null)
    {
        parent::__construct($data, $args);

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

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

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

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

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

    protected function _register_controls()
    {
        // Seção de conteúdo
        $this->start_controls_section(
            'content_section',
            [
                'label' => __('Content', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        // Controle para imagens alternativas
        $this->add_control(
            'fallback_images',
            [
                'label' => __('Alternative Images', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::GALLERY,
                'description' => __('Images to be displayed if the product does not have a gallery.', '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' => 'medium',
                '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 size of the gallery images.', 'link-nacional-wp-crowdfunding-extension'),
            ]
        );

        $this->end_controls_section();

        // Seção de estilo
        $this->start_controls_section(
            'style_section',
            [
                'label' => __('Style', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        // Altura da imagem
        $this->add_control(
            'image_height',
            [
                'label' => __('Image Height', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'default' => [
                    'size' => 200,
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-gallery-image' => 'height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        // Largura da imagem
        $this->add_control(
            'image_width',
            [
                'label' => __('Image Width', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'default' => [
                    'size' => 200,
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-gallery-image' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        // Justificação horizontal
        // Justificação horizontal
        $this->add_control(
            'gallery_justify',
            [
                'label' => __('Gallery Justify Content', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'space-around' => [
                        'title' => __('Space Around', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-justify-space-around-h',
                    ],
                    'space-between' => [
                        'title' => __('Space Between', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-justify-space-between-h',
                    ],
                    'space-evenly' => [
                        'title' => __('Space Evenly', 'link-nacional-wp-crowdfunding-extension'),
                        'icon' => 'eicon-justify-space-evenly-h',
                    ],
                ],
                'default' => 'space-between',
                'selectors' => [
                    '{{WRAPPER}} .lkn-product-gallery-container' => 'justify-content: {{VALUE}};',
                ],
            ]
        );


        // Alinhamento vertical
        $this->add_control(
            'gallery_align',
            [
                'label' => __('Gallery 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-gallery-container' => 'align-items: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $product_id = get_the_ID();
        $gallery_ids = get_post_meta($product_id, '_product_image_gallery', true);

        $gallery_images = [];

        // Recupera imagens da galeria
        if ($gallery_ids) {
            $gallery_ids = explode(',', $gallery_ids);
            foreach ($gallery_ids as $attachment_id) {
                $image = wp_get_attachment_image($attachment_id, $settings['image_size']);
                $full_image_url = wp_get_attachment_image_url($attachment_id, 'full'); // URL da imagem em tamanho completo
                if ($image) {
                    $gallery_images[] = '<a href="' . esc_url($full_image_url) . '">' . str_replace('class="', 'class="lkn-product-gallery-image ', $image) . '</a>';
                }
            }
        }

        // Caso não tenha imagens na galeria, usa imagens alternativas
        if (empty($gallery_images) && !empty($settings['fallback_images'])) {
            foreach ($settings['fallback_images'] as $fallback_image) {
                $image = wp_get_attachment_image($fallback_image['id'], $settings['image_size']);
                $full_image_url = wp_get_attachment_image_url($fallback_image['id'], 'full'); // URL da imagem em tamanho completo
                if ($image) {
                    $gallery_images[] = '<a href="' . esc_url($full_image_url) . '">' . str_replace('class="', 'class="lkn-product-gallery-image ', $image) . '</a>';
                }
            }
        }

        // Renderiza a galeria ou exibe mensagens padrão
        if (!empty($gallery_images)) {
            echo '<div class="lkn-product-gallery-container" style="display: flex; gap: 10px; flex-wrap: wrap;">';
            foreach ($gallery_images as $image) {
                echo '<div class="lkn-product-gallery" style="display: flex;">';
                echo wp_kses_post($image);
                echo '</div>';
            }
            echo '</div>';
        }

        // Renderiza imagens padrão no editor do Elementor
        if ((\Elementor\Plugin::$instance->editor->is_edit_mode() || is_preview() || get_post_type() !== 'product') && empty($settings['fallback_images'])) {
            echo '<div class="lkn-product-gallery-container" style="display: flex; gap: 10px; flex-wrap: wrap;">';
            for ($i = 0; $i < 3; $i++) {
                echo '<div class="lkn-product-gallery" style="display: flex;">';
                $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');
                $thumbnail = str_replace('class="', 'class="lkn-product-gallery-image ', $thumbnail);

                echo '<a href="' . esc_url($full_image_url) . '">';
                echo wp_kses_post($thumbnail);
                echo '</a>';
                echo '</div>';
            }
            echo '</div>';
        } else {
            echo '';
        }
    }
}
