<?php
/**
 * Widget Elementor: Lista Annunci
 *
 * Mostra la lista degli ultimi annunci funebri
 *
 * @package AnnunciFunebri
 * @since 4.8.0
 */

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

class ANNFU_Widget_Lista_Annunci extends ANNFU_Widget_Base {

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

    public function get_title() {
        return __('Lista Annunci', 'annuncifunebri-onoranza');
    }

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

    protected function ha_dati_widget() {
        return true;
    }

    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' => 'Ultimi Annunci',
                'placeholder' => 'Ultimi Annunci',
            ]
        );

        $this->add_control(
            'limite',
            [
                'label' => __('Numero Annunci', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 6,
                'min' => 1,
                'max' => 50,
                'description' => __('Numero massimo di annunci da mostrare', 'annuncifunebri-onoranza'),
            ]
        );

        $this->add_control(
            'layout',
            [
                'label' => __('Layout', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'griglia',
                'options' => [
                    'griglia' => __('Griglia', 'annuncifunebri-onoranza'),
                    'lista' => __('Lista', 'annuncifunebri-onoranza'),
                    'carousel' => __('Carousel', 'annuncifunebri-onoranza'),
                ],
            ]
        );

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

        $this->add_control(
            'annunci_per_slide',
            [
                'label' => __('Annunci per Slide', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 3,
                'min' => 1,
                'max' => 6,
                'description' => __('Numero di annunci visibili contemporaneamente in ogni slide', 'annuncifunebri-onoranza'),
                'condition' => [
                    'layout' => 'carousel',
                ],
            ]
        );

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

        $this->add_control(
            'mostra_tipo',
            [
                'label' => __('Mostra Tipo Annuncio', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Sì', 'annuncifunebri-onoranza'),
                'label_off' => __('No', 'annuncifunebri-onoranza'),
                'return_value' => 'yes',
                'default' => 'yes',
                'description' => __('Mostra badge per anniversario/ringraziamento', 'annuncifunebri-onoranza'),
            ]
        );

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

        $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-lista-annunci-titolo',
            ]
        );

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

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'tipografia_nome',
                'label' => __('Tipografia Nome', 'annuncifunebri-onoranza'),
                'selector' => '{{WRAPPER}} .annfu-annuncio-nome',
            ]
        );

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

        $this->add_control(
            'colore_sfondo_card',
            [
                'label' => __('Colore Sfondo Card', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .annfu-annuncio-card' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'bordo_card',
                'label' => __('Bordo Card', 'annuncifunebri-onoranza'),
                'selector' => '{{WRAPPER}} .annfu-annuncio-card',
            ]
        );

        $this->add_responsive_control(
            'spaziatura_card',
            [
                'label' => __('Spaziatura Card', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .annfu-annuncio-card' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'margine_card',
            [
                'label' => __('Margine tra Card', 'annuncifunebri-onoranza'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 100,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 20,
                ],
                'selectors' => [
                    '{{WRAPPER}} .annfu-annuncio-card' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

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

        $titolo = $settings['titolo'];
        $limite = intval($settings['limite']);
        $layout = $settings['layout'];
        $colonne = $settings['colonne'];
        $annunci_per_slide = isset($settings['annunci_per_slide']) ? intval($settings['annunci_per_slide']) : 3;
        $mostra_foto = $settings['mostra_foto'] === 'yes';
        $mostra_tipo = $settings['mostra_tipo'] === 'yes';
        $mostra_date = $settings['mostra_date'] === 'yes';

        $onoranza_id = get_option('annfu_onoranza_funebre_id');
        $api_url = defined('ANNFU_SITE_API') ? ANNFU_SITE_API : '';

        if (empty($api_url) || empty($onoranza_id)) {
            if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                echo '<p>' . esc_html__('API non configurata correttamente', 'annuncifunebri-onoranza') . '</p>';
            }
            return;
        }

        $url = $api_url . '/v2/annunci?limit=' . $limite . '&onoranza_funebre_id=' . $onoranza_id;

        $col_class = $layout === 'griglia' ? 'col-md-' . (12 / intval($colonne)) : 'col-12';
        $wrapper_class = 'annfu-lista-annunci-' . $layout;

        ?>
        <div class="annfu-lista-annunci-wrapper <?php echo esc_attr($wrapper_class); ?>"
             x-data="annfuListaAnnunci('<?php echo esc_url($url); ?>', <?php echo esc_attr($annunci_per_slide); ?>)">

            <?php if (!empty($titolo)): ?>
                <h3 class="annfu-lista-annunci-titolo"><?php echo esc_html($titolo); ?></h3>
            <?php endif; ?>

            <div x-show="isLoading" class="annfu-loading">
                <?php echo esc_html__('Caricamento...', 'annuncifunebri-onoranza'); ?>
            </div>

            <div x-show="!isLoading" class="annfu-annunci-container">
                <?php if ($layout === 'carousel'): ?>
                    <div class="annfu-carousel">
                        <button @click="prevSlide" class="annfu-carousel-prev">‹</button>
                        <div class="annfu-carousel-inner">
                            <div class="annfu-carousel-track" :style="`transform: translateX(-${currentSlide * 100}%)`">
                                <template x-for="(slide, slideIndex) in slides" :key="'slide-' + slideIndex">
                                    <div class="annfu-carousel-slide">
                                        <div class="annfu-carousel-slide-grid" :style="`--annunci-per-slide: ${annunciPerSlide}`">
                                            <template x-for="annuncio in slide" :key="annuncio.slug">
                                                <div class="annfu-annuncio-card">
                                                    <?php echo $this->render_annuncio_template($mostra_foto, $mostra_tipo, $mostra_date); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                                                </div>
                                            </template>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                        <button @click="nextSlide" class="annfu-carousel-next">›</button>
                    </div>
                <?php else: ?>
                    <div class="row annfu-annunci-grid">
                        <template x-for="annuncio in annunci" :key="annuncio.slug">
                            <div class="<?php echo esc_attr($col_class); ?>">
                                <div class="annfu-annuncio-card">
                                    <?php echo $this->render_annuncio_template($mostra_foto, $mostra_tipo, $mostra_date); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                                </div>
                            </div>
                        </template>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('annfuListaAnnunci', (url, annunciPerSlideDesktop = 3) => ({
                isLoading: true,
                annunci: [],
                annunciPerSlideDesktop: annunciPerSlideDesktop,
                currentSlide: 0,
                windowWidth: window.innerWidth,

                init() {
                    this.fetchAnnunci(url);
                    window.addEventListener('resize', () => {
                        this.windowWidth = window.innerWidth;
                        if (this.currentSlide >= this.totalSlides) {
                            this.currentSlide = Math.max(0, this.totalSlides - 1);
                        }
                    });
                },

                get annunciPerSlide() {
                    if (this.windowWidth < 576) {
                        return 1;
                    } else if (this.windowWidth < 992) {
                        return 2;
                    }
                    return this.annunciPerSlideDesktop;
                },

                get slides() {
                    const result = [];
                    const perSlide = this.annunciPerSlide;
                    for (let i = 0; i < this.annunci.length; i += perSlide) {
                        result.push(this.annunci.slice(i, i + perSlide));
                    }
                    return result;
                },

                get totalSlides() {
                    return this.slides.length;
                },

                fetchAnnunci(url) {
                    fetch(url)
                        .then(response => response.json())
                        .then(data => {
                            this.annunci = data.data || [];
                            this.isLoading = false;
                        })
                        .catch(error => {
                            console.error('Errore caricamento annunci:', error);
                            this.isLoading = false;
                        });
                },

                nextSlide() {
                    if (this.totalSlides > 0) {
                        this.currentSlide = (this.currentSlide + 1) % this.totalSlides;
                    }
                },

                prevSlide() {
                    if (this.totalSlides > 0) {
                        this.currentSlide = this.currentSlide === 0 ? this.totalSlides - 1 : this.currentSlide - 1;
                    }
                }
            }));
        });
        </script>
        <?php
    }

    private function render_annuncio_template($mostra_foto, $mostra_tipo, $mostra_date) {
        ob_start();
        $page_annuncio = defined('ANNFU_PAGE_ANNUNCIO') ? ANNFU_PAGE_ANNUNCIO : 'annuncio';
        ?>
        <a :href="`<?php echo esc_url(get_site_url() . '/' . $page_annuncio); ?>/${annuncio.comune?.slug || 'comune'}/${annuncio.slug}`"
           class="annfu-annuncio-link">

            <?php if ($mostra_tipo): ?>
                <template x-if="annuncio.tipoAnnuncio === 'anniversario'">
                    <div class="annfu-badge annfu-badge-anniversario">
                        <?php echo esc_html__('Anniversario', 'annuncifunebri-onoranza'); ?>
                    </div>
                </template>
                <template x-if="annuncio.tipoAnnuncio === 'ringraziamento'">
                    <div class="annfu-badge annfu-badge-ringraziamento">
                        <?php echo esc_html__('Ringraziamento', 'annuncifunebri-onoranza'); ?>
                    </div>
                </template>
            <?php endif; ?>

            <?php if ($mostra_foto): ?>
                <div class="annfu-annuncio-foto">
                    <img :src="annuncio.foto" :alt="annuncio.nominativo" class="annfu-foto-img">
                </div>
            <?php endif; ?>

            <div class="annfu-annuncio-contenuto">
                <h4 class="annfu-annuncio-nome" x-html="annuncio.nominativoCompleto || annuncio.nominativo"></h4>

                <?php if ($mostra_date): ?>
                    <div class="annfu-annuncio-date">
                        <span x-show="annuncio.dataNascita">
                            <span x-text="new Date(annuncio.dataNascita).toLocaleDateString('it-IT')"></span>
                        </span>
                        <span x-show="annuncio.dataMorte">
                            - <span x-text="new Date(annuncio.dataMorte).toLocaleDateString('it-IT')"></span>
                        </span>
                    </div>
                <?php endif; ?>
            </div>
        </a>
        <?php
        return ob_get_clean();
    }
}
