<?php

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

class ETN_EGR_Shortcode {

    private $opt_data   = ETN_EGR_OPTION_DATA;
    private $opt_styles = ETN_EGR_OPTION_STYLES;

    public function __construct() {
        add_shortcode('etn_egr_reviews_carousel', [$this, 'render_shortcode']);
        add_action('wp_footer', [$this, 'render_schema_json_ld'], 998);
    }

    public function render_shortcode($atts = []) {
        etn_egr_enqueue_front_assets(true);
        $reviews_all = etn_egr_get_all_reviews();
        // Si la lista unificada está vacía pero hay reseñas manuales, usarlas (evita fallos de caché o merge)
        if (empty($reviews_all)) {
            $manual = get_option(ETN_EGR_OPTION_MANUAL_REVIEWS, []);
            $reviews_all = is_array($manual) ? $manual : [];
        }
        if (empty($reviews_all)) {
            return esc_html__('No data to show. Sync from the admin or add manual reviews. Also check your filters (minimum stars, exclude empty text).', 'etchenet-reviews-for-google-business');
        }

        $s = get_option($this->opt_styles, etn_egr_get_default_styles());

        // Permitir ajustes por widget mediante atributos del shortcode
        // Ejemplo: [etn_egr_reviews_carousel excerpt=\"180\"]
        $default_excerpt = isset($s['excerpt_length']) && (int) $s['excerpt_length'] > 0 ? (int) $s['excerpt_length'] : 150;
        $atts = shortcode_atts(
            [
                'excerpt'   => $default_excerpt,
                // Reservado por si en el futuro se vuelve a usar "leer más" dentro del slider
                'read_more' => isset($s['show_read_more']) ? (int) $s['show_read_more'] : 0,
                'min_stars' => isset($s['min_stars']) ? (int) $s['min_stars'] : 1,
            ],
            $atts,
            'etn_egr_reviews_carousel'
        );

        // Filtros de reseñas (usando defaults globales + overrides del widget)
        $min_stars     = (int) $atts['min_stars'];
        $exclude_empty = !empty($s['exclude_empty']);
        // Longitud de extracto: un solo valor entero para TODAS las tarjetas (Google y manuales)
        $excerpt_len   = (int) $atts['excerpt'];
        if ($excerpt_len < 50) {
            $excerpt_len = 50;
        }
        if ($excerpt_len > 500) {
            $excerpt_len = 500;
        }
        // Actualmente el botón \"Leer más\" solo se usa en el sidebar,
        // pero dejamos este flag preparado por si se quiere usar por widget en el futuro.
        $show_read_more = !empty($atts['read_more']);

        $reviews = array_filter($reviews_all, function ($r) use ($min_stars, $exclude_empty) {
            $rating = isset($r['rating']) ? (float) $r['rating'] : 0;
            if ($rating < $min_stars) {
                return false;
            }
            $text = isset($r['text']) ? trim($r['text']) : '';
            if ($exclude_empty && $text === '') {
                return false;
            }
            return true;
        });

        if (empty($reviews)) {
            return esc_html__('No reviews match the current filter settings.', 'etchenet-reviews-for-google-business');
        }

        ob_start();

        $aspect = isset($s['card_aspect_ratio']) && in_array($s['card_aspect_ratio'], ['16_9', '4_3', 'auto'], true) ? $s['card_aspect_ratio'] : '16_9';
        $card_padding = isset($s['card_padding']) ? max(8, min(48, (int) $s['card_padding'])) : 16;
        $card_gap = isset($s['card_gap']) ? max(0, min(40, (int) $s['card_gap'])) : 12;
        $read_more_gap = isset($s['card_read_more_gap']) ? max(0, min(24, (int) $s['card_read_more_gap'])) : 4;
        $arrow_size = isset($s['arrow_size']) ? max(24, min(80, (int) $s['arrow_size'])) : 40;
        $arrow_circle = !empty($s['arrows_circle']);
        $arrow_bg = isset($s['arrow_bg_color']) ? $s['arrow_bg_color'] : '#ffffff';
        $arrow_icon = isset($s['arrow_icon_color']) ? $s['arrow_icon_color'] : '#555555';
        $arrow_pos_h = isset($s['arrow_pos_h']) && in_array($s['arrow_pos_h'], array('limit', 'exterior', 'interior'), true) ? $s['arrow_pos_h'] : 'limit';
        $arrow_pos_v = isset($s['arrow_pos_v']) && in_array($s['arrow_pos_v'], array('top', 'middle', 'bottom'), true) ? $s['arrow_pos_v'] : 'middle';
        // Variables CSS (proporciones, márgenes, flechas) vía inline style encolado
        $vars_css = ':root{'
            . '--etn-egr-bg:' . esc_attr($s['bg_card']) . ';'
            . '--etn-egr-cn:' . esc_attr($s['c_name']) . ';'
            . '--etn-egr-ct:' . esc_attr($s['c_text']) . ';'
            . '--etn-egr-cs:' . esc_attr($s['c_star']) . ';'
            . '--etn-egr-br:' . (int) $s['border_radius'] . 'px;'
            . '--etn-egr-card-padding:' . (int) $card_padding . 'px;'
            . '--etn-egr-card-gap:' . (int) $card_gap . 'px;'
            . '--etn-egr-read-more-gap:' . (int) $read_more_gap . 'px;'
            . '--etn-egr-arrow-size:' . (int) $arrow_size . 'px;'
            . '--etn-egr-arrow-bg:' . esc_attr($arrow_bg) . ';'
            . '--etn-egr-arrow-color:' . esc_attr($arrow_icon) . ';'
            . '--etn-egr-arrow-circle:' . ($arrow_circle ? '1' : '0') . ';'
            . '}';
        if (function_exists('wp_add_inline_style')) {
            wp_add_inline_style('etn-egr-style', $vars_css);
        }
        ?>
        <div class="etn-egr-slider-container etn-egr-aspect-<?php echo esc_attr($aspect); ?> etn-egr-arrow-h-<?php echo esc_attr($arrow_pos_h); ?> etn-egr-arrow-v-<?php echo esc_attr($arrow_pos_v); ?> <?php echo !empty($s['equal_height']) ? 'etn-egr-equal-height' : ''; ?> <?php echo $arrow_circle ? '' : 'etn-egr-arrows-no-circle'; ?>">
            <div class="swiper etn-egr-slider">
                <div class="swiper-wrapper">
                    <?php foreach ($reviews as $r) : 
                        $raw_text = isset($r['text']) ? (string) $r['text'] : '';
                        $full_text = etn_egr_normalize_review_text($raw_text);
                        list($display_text, $needs_read_more) = etn_egr_make_excerpt($full_text, $excerpt_len);
                        // Mostrar "Leer más" siempre que haya más texto que lo mostrado (por si acaso)
                        if (!$needs_read_more && $full_text !== '' && function_exists('mb_strlen')) {
                            $needs_read_more = (mb_strlen($full_text, 'UTF-8') > mb_strlen($display_text, 'UTF-8'));
                        }
                        if ($needs_read_more) {
                            $needs_read_more = $show_read_more;
                        }

                        // Texto completo seguro para atributo (base64 UTF-8)
                        $full_b64 = base64_encode($full_text);
                        ?>
                        <div class="swiper-slide">
                            <div class="etn-egr-card etn-egr-card-slider"<?php echo ($aspect === 'auto' && !empty($s['equal_height'])) ? ' style="height:100%;"' : ''; ?>>
                                <div class="etn-egr-author">
                                    <?php if (!empty($s['show_avatar'])) : ?>
                                        <?php $avatar_src = !empty($r['profile_photo_url']) ? $r['profile_photo_url'] : ETN_EGR_DEFAULT_AVATAR_URL; ?>
                                        <img src="<?php echo esc_url($avatar_src); ?>" class="etn-egr-avatar" alt="<?php echo esc_attr($r['author_name'] ?? ''); ?>" loading="lazy">
                                    <?php endif; ?>
                                    <span class="etn-egr-name"><?php echo esc_html($r['author_name'] ?? ''); ?></span>
                                    <?php if (!empty($s['show_google_logo'])) : ?>
                                        <img src="<?php echo esc_url(ETN_EGR_GOOGLE_ICON_URL); ?>" class="etn-egr-g-icon" width="20" alt="Google">
                                    <?php endif; ?>
                                </div>
                                <div class="etn-egr-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;">
                                    <?php
                                    $rating = isset($r['rating']) ? (int) $r['rating'] : 0;
                                    for ($i = 0; $i < $rating; $i++) {
                                        echo '<span class="etn-egr-star">★</span>';
                                    }
                                    ?>
                                </div>
                                <p class="etn-egr-text" style="color:<?php echo esc_attr($s['c_text']); ?>;">
                                    <?php echo esc_html($display_text); ?>
                                    <?php if ($needs_read_more) : ?>...<?php endif; ?>
                                </p>
                                <?php if ($needs_read_more) : ?>
                                    <div class="etn-egr-read-more-wrap">
                                        <a href="#"
                                           class="etn-egr-read-more etn-egr-read-more-slider"
                                           data-full-text-b64="<?php echo esc_attr($full_b64); ?>">
                                            <?php echo esc_html__('Read more', 'etchenet-reviews-for-google-business'); ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <?php if (!empty($s['dots'])) : ?>
                    <div class="swiper-pagination"></div>
                <?php endif; ?>
            </div>
            <?php if (!empty($s['arrows'])) : ?>
                <div class="swiper-button-next"></div>
                <div class="swiper-button-prev"></div>
            <?php endif; ?>
        </div>

        <!-- Modal Leer más (z-index alto para quedar por encima del panel lateral) -->
        <div id="etn-egr-modal" class="etn-egr-modal" style="display:none;">
            <div class="etn-egr-modal-content">
                <button type="button" class="etn-egr-modal-close" aria-label="<?php echo esc_attr__('Close', 'etchenet-reviews-for-google-business'); ?>">&times;</button>
                <div id="etn-egr-modal-body"></div>
            </div>
        </div>
        <?php

        return ob_get_clean();
    }

    /**
     * Esquema JSON-LD para Rich Snippets (rating + reviewCount).
     */
    public function render_schema_json_ld() {
        $s = get_option($this->opt_styles, etn_egr_get_default_styles());
        if (empty($s['rich_snippets'])) {
            return;
        }

        $data = get_option($this->opt_data);
        if (empty($data['rating']) || empty($data['user_ratings_total'])) {
            return;
        }

        $schema = [
            '@context' => 'https://schema.org',
            '@type'    => 'LocalBusiness',
            'name'     => !empty($data['name']) ? $data['name'] : get_bloginfo('name'),
            'aggregateRating' => [
                '@type'       => 'AggregateRating',
                'ratingValue' => (float) $data['rating'],
                'reviewCount' => (int) $data['user_ratings_total'],
            ],
        ];

        echo '<script type="application/ld+json">' .
            wp_json_encode($schema, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) .
            '</script>';
    }
}

