<?php
/**
 * Widget Elementor: Collage Foto
 *
 * Mostra un collage di foto multiple dalla galleria
 *
 * @package AnnunciFunebri
 * @since 4.8.0
 */

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

class ANNFU_Widget_Collage extends ANNFU_Widget_Base {

    public function get_name() {
        return 'annfu_collage';
    }

    public function get_title() {
        return __('Collage Foto', 'annuncifunebri-onoranza');
    }

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

    public function get_script_depends() {
        return array('annfu-collage-lightbox');
    }

    protected function ha_dati_widget() {
        $galleria = $this->ottieni_campo('fotoCordogli', []);
        return !empty($galleria) && is_array($galleria);
    }

    protected function register_controls() {
        // === TAB CONTENT ===
        $this->start_controls_section(
            'sezione_contenuto',
            [
                'label' => __('Contenuto', 'annuncifunebri-onoranza'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'titolo',
            [
                'label' => __('Titolo', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => 'Galleria Ricordi',
                'placeholder' => 'Galleria Ricordi',
            ]
        );

        $this->add_control(
            'layout',
            [
                'label' => __('Layout', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'griglia',
                'options' => [
                    'griglia' => __('Griglia Regolare', 'annuncifunebri-onoranza'),
                    'masonry' => __('Masonry (Pinterest)', 'annuncifunebri-onoranza'),
                    'mosaico' => __('Mosaico', 'annuncifunebri-onoranza'),
                    'slider' => __('Slider', 'annuncifunebri-onoranza'),
                ],
            ]
        );

        $this->add_control(
            'colonne',
            [
                'label' => __('Numero Colonne', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => '3',
                'options' => [
                    '2' => __('2', 'annuncifunebri-onoranza'),
                    '3' => __('3', 'annuncifunebri-onoranza'),
                    '4' => __('4', 'annuncifunebri-onoranza'),
                    '5' => __('5', 'annuncifunebri-onoranza'),
                    '6' => __('6', 'annuncifunebri-onoranza'),
                ],
                'condition' => [
                    'layout' => ['griglia', 'masonry'],
                ],
            ]
        );

        $this->add_control(
            'limite',
            [
                'label' => __('Numero Massimo Foto', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 0,
                'min' => 0,
                'description' => __('0 = mostra tutte', 'annuncifunebri-onoranza'),
            ]
        );

        $this->add_control(
            'mostra_didascalie',
            [
                'label' => __('Mostra Didascalie', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Sì', 'annuncifunebri-onoranza'),
                'label_off' => __('No', 'annuncifunebri-onoranza'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'hover_effect',
            [
                'label' => __('Effetto Hover', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'zoom',
                'options' => [
                    'none' => __('Nessuno', 'annuncifunebri-onoranza'),
                    'zoom' => __('Zoom', 'annuncifunebri-onoranza'),
                    'overlay' => __('Overlay', 'annuncifunebri-onoranza'),
                    'grayscale' => __('Grayscale', 'annuncifunebri-onoranza'),
                ],
            ]
        );

        $this->add_control(
            'lightbox',
            [
                'label' => __('Abilita Lightbox', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Sì', 'annuncifunebri-onoranza'),
                'label_off' => __('No', 'annuncifunebri-onoranza'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => __('Click sulla foto per ingrandirla', 'annuncifunebri-onoranza'),
            ]
        );

        $this->add_control(
            'aspect_ratio',
            [
                'label' => __('Rapporto Aspetto', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => '1-1',
                'options' => [
                    '1-1' => __('Quadrato (1:1)', 'annuncifunebri-onoranza'),
                    '4-3' => __('Landscape (4:3)', 'annuncifunebri-onoranza'),
                    '16-9' => __('Widescreen (16:9)', 'annuncifunebri-onoranza'),
                    '3-4' => __('Portrait (3:4)', 'annuncifunebri-onoranza'),
                    'auto' => __('Originale', 'annuncifunebri-onoranza'),
                ],
                'condition' => [
                    'layout' => ['griglia'],
                ],
            ]
        );

        $this->end_controls_section();

        // === TAB STYLE ===
        $this->start_controls_section(
            'sezione_stile',
            [
                'label' => __('Stile', 'annuncifunebri-onoranza'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'tipografia_titolo',
                'label' => __('Tipografia Titolo', 'annuncifunebri-onoranza'),
                'selector' => '{{WRAPPER}} .annfu-collage-titolo',
            ]
        );

        $this->add_control(
            'colore_titolo',
            [
                'label' => __('Colore Titolo', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .annfu-collage-titolo' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'gap',
            [
                'label' => __('Spaziatura tra Foto', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 50,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 10,
                ],
                'selectors' => [
                    '{{WRAPPER}} .annfu-collage-grid' => 'gap: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'bordo_foto',
                'label' => __('Bordo Foto', 'annuncifunebri-onoranza'),
                'selector' => '{{WRAPPER}} .annfu-collage-item img',
            ]
        );

        $this->add_responsive_control(
            'border_radius',
            [
                'label' => __('Raggio Bordo', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 50,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .annfu-collage-item img' => 'border-radius: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'ombra_foto',
                'label' => __('Ombra Foto', 'annuncifunebri-onoranza'),
                'selector' => '{{WRAPPER}} .annfu-collage-item img',
            ]
        );

        $this->add_control(
            'colore_overlay',
            [
                'label' => __('Colore Overlay (hover)', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => 'rgba(0,0,0,0.5)',
                'selectors' => [
                    '{{WRAPPER}} .annfu-collage-item::after' => 'background-color: {{VALUE}};',
                ],
                'condition' => [
                    'hover_effect' => 'overlay',
                ],
            ]
        );

        $this->end_controls_section();
    }

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

        if (\Elementor\Plugin::$instance->editor->is_edit_mode() && !$this->ha_dati_widget()) {
            $this->render_placeholder_editor('eicon-gallery-grid', __('Collage Foto', 'annuncifunebri-onoranza'), __('Griglia di foto dalla galleria', 'annuncifunebri-onoranza'));
            return;
        }

        if (!$this->ha_dati_widget()) {
            return;
        }

        $galleria = $this->ottieni_campo('fotoCordogli', []);
        $titolo = $settings['titolo'];
        $layout = $settings['layout'];
        $colonne = $settings['colonne'];
        $limite = intval($settings['limite']);
        $mostra_didascalie = $settings['mostra_didascalie'] === 'yes';
        $hover_effect = $settings['hover_effect'];
        $lightbox = $settings['lightbox'] === 'yes';
        $aspect_ratio = $settings['aspect_ratio'];

        // Applica limite se specificato
        if ($limite > 0) {
            $galleria = array_slice($galleria, 0, $limite);
        }

        $wrapper_class = 'annfu-collage-wrapper annfu-layout-' . $layout . ' annfu-hover-' . $hover_effect;
        $grid_class = 'annfu-collage-grid annfu-cols-' . $colonne . ' annfu-ratio-' . $aspect_ratio;

        ?>
        <div class="<?php echo esc_attr($wrapper_class); ?>">
            <?php if (!empty($titolo)): ?>
                <h3 class="annfu-collage-titolo"><?php echo esc_html($titolo); ?></h3>
            <?php endif; ?>

            <?php if ($layout === 'slider'): ?>
                <div class="annfu-collage-slider" x-data="annfuCollageSlider(<?php echo count($galleria); ?>)">
                    <div class="annfu-slider-container">
                        <?php foreach ($galleria as $index => $foto): ?>
                            <div class="annfu-collage-item annfu-slider-item"
                                 x-show="currentSlide === <?php echo esc_attr( $index ); ?>"
                                 x-transition>
                                <?php $this->render_foto_item($foto, $mostra_didascalie, $lightbox); ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button @click="prevSlide" class="annfu-slider-prev">‹</button>
                    <button @click="nextSlide" class="annfu-slider-next">›</button>
                    <div class="annfu-slider-counter">
                        <span class="current" x-text="currentSlide + 1">1</span> / <span class="total"><?php echo count($galleria); ?></span>
                    </div>
                </div>
                <script>
                document.addEventListener('alpine:init', () => {
                    Alpine.data('annfuCollageSlider', (total) => ({
                        currentSlide: 0,
                        totalSlides: total,
                        nextSlide() {
                            this.currentSlide = (this.currentSlide + 1) % this.totalSlides;
                        },
                        prevSlide() {
                            this.currentSlide = this.currentSlide === 0 ? this.totalSlides - 1 : this.currentSlide - 1;
                        }
                    }));
                });
                </script>
            <?php else: ?>
                <div class="<?php echo esc_attr($grid_class); ?>">
                    <?php foreach ($galleria as $foto): ?>
                        <div class="annfu-collage-item">
                            <?php $this->render_foto_item($foto, $mostra_didascalie, $lightbox); ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($lightbox): ?>
            <div class="annfu-collage-lightbox">
                <span class="annfu-collage-lightbox-close">&times;</span>
                <span class="annfu-collage-lightbox-nav annfu-collage-lightbox-prev">‹</span>
                <span class="annfu-collage-lightbox-nav annfu-collage-lightbox-next">›</span>
                <img src="" alt="">
                <div class="annfu-collage-lightbox-counter">
                    <span class="current">1</span> / <span class="total">1</span>
                </div>
            </div>
        <?php endif; ?>
        <?php
    }

    private function render_foto_item($foto, $mostra_didascalie, $lightbox) {
        $url = is_array($foto) ? ($foto['url'] ?? $foto) : $foto;
        $didascalia = is_array($foto) ? ($foto['didascalia'] ?? '') : '';

        if ($lightbox):
            ?>
            <img src="<?php echo esc_url($url); ?>"
                 alt="<?php echo esc_attr($didascalia); ?>"
                 class="annfu-lightbox-trigger"
                 data-fullsize="<?php echo esc_url($url); ?>">
        <?php else: ?>
            <img src="<?php echo esc_url($url); ?>"
                 alt="<?php echo esc_attr($didascalia); ?>">
        <?php endif;

        if ($mostra_didascalie && !empty($didascalia)):
            ?>
            <div class="annfu-collage-caption">
                <?php echo esc_html($didascalia); ?>
            </div>
        <?php endif;
    }
}
