<?php

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

class ETN_EGR_Badge {

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

    public function __construct() {
        add_action('wp_footer', array($this, 'render_floating_badge'), 999);
    }

    public function render_floating_badge() {
        $s = get_option($this->opt_styles, etn_egr_get_default_styles());
        if (empty($s['show_badge'])) {
            return;
        }

        $reviews = etn_egr_get_all_reviews();
        if (empty($reviews)) {
            $reviews = get_option(ETN_EGR_OPTION_MANUAL_REVIEWS, []);
            $reviews = is_array($reviews) ? $reviews : [];
        }
        if (empty($reviews)) {
            return;
        }

        etn_egr_enqueue_front_assets(false);

        $side_css = ($s['badge_pos'] === 'left')
            ? 'left:' . (int) $s['badge_m_side'] . 'px;'
            : 'right:' . (int) $s['badge_m_side'] . 'px;';

        // Aplicar filtros igual que en el shortcode
        $min_stars     = isset($s['min_stars']) ? (int) $s['min_stars'] : 1;
        $exclude_empty = !empty($s['exclude_empty']);
        $excerpt_len   = isset($s['excerpt_length']) ? (int) $s['excerpt_length'] : 150;
        if ($excerpt_len < 50) {
            $excerpt_len = 50;
        }
        if ($excerpt_len > 500) {
            $excerpt_len = 500;
        }
        $show_read_more = !empty($s['show_read_more']);

        $filtered_reviews = array_filter($reviews, 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;
        });

        $max_in_panel = (int) ($s['sidebar_max_reviews'] ?? 0);
        $panel_reviews = $max_in_panel > 0 ? array_slice($filtered_reviews, 0, $max_in_panel) : $filtered_reviews;
        $total  = count($filtered_reviews);
        $rating = $total > 0
            ? array_sum(array_map(function ($r) { return (float) ($r['rating'] ?? 0); }, $filtered_reviews)) / $total
            : 0;
        $write_review_url = !empty($s['write_review_url']) ? esc_url($s['write_review_url']) : '';

        ?>
        <!-- Badge flotante clickeable -->
        <div class="etn-egr-badge-fixed etn-egr-badge-clickable"
             style="position:fixed;z-index:9999;
                    bottom:<?php echo (int) $s['badge_m_bottom']; ?>px;
                    <?php echo esc_attr( $side_css ); ?>
                    background:#ffffff;
                    border-radius:<?php echo (int) $s['border_radius']; ?>px;
                    padding:<?php echo (int) $s['badge_padding']; ?>px;
                    box-shadow:0 4px 12px rgba(0,0,0,0.15);
                    cursor:pointer;
                    transition:transform 0.2s ease;">
            <div style="display:flex;align-items:center;gap:10px;">
                <img src="<?php echo esc_url(ETN_EGR_GOOGLE_ICON_URL); ?>"
                     width="32" alt="<?php echo esc_attr__('Google Reviews', 'etchenet-reviews-for-google-business'); ?>">
                <div class="etn-egr-b-data" style="line-height:1.2;">
                    <div class="etn-egr-b-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:14px;">
                        ★★★★★
                    </div>
                    <div class="etn-egr-b-txt" style="font-size:13px;color:#333;">
                        <strong><?php echo esc_html(number_format_i18n($rating, 1)); ?></strong>
                        <span style="color:#999;">/ 5.0</span><br>
                        <?php
                        /* translators: 1: number of reviews (singular: review, plural: reviews) */
                        echo esc_html( sprintf( _n( '%d Google review', '%d Google reviews', $total, 'etchenet-reviews-for-google-business' ), $total ) );
                        ?>
                    </div>
                </div>
                <?php if ($write_review_url) : ?>
                <a href="<?php echo esc_url( $write_review_url ); ?>" class="etn-egr-badge-write-review" target="_blank" rel="noopener noreferrer"
                   title="<?php echo esc_attr__('Write a review', 'etchenet-reviews-for-google-business'); ?>"
                   style="flex-shrink:0;display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;background:<?php echo esc_attr($s['c_star']); ?>;color:#fff;font-size:18px;line-height:1;text-decoration:none;font-weight:bold;">+</a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Overlay de fondo -->
        <div class="etn-egr-sidebar-overlay" style="display:none;"></div>

        <?php
        $header_sticky = !empty($s['sidebar_header_sticky']);
        $pad = (int) ($s['sidebar_padding'] ?? 20);
        $panel_flex = $header_sticky ? 'display:flex;flex-direction:column;' : '';
        $scroll_flex = $header_sticky ? 'flex:1;min-height:0;' : 'height:100%;';
        ?>
        <!-- Panel lateral: role dialog y aria para accesibilidad -->
        <div class="etn-egr-sidebar-panel" 
             role="dialog"
             aria-modal="true"
             aria-label="<?php echo esc_attr__('Google reviews', 'etchenet-reviews-for-google-business'); ?>"
             data-panel-layout="<?php echo $header_sticky ? 'flex' : 'block'; ?>"
             style="display:none;
                    position:fixed;
                    left:0;
                    top:0;
                    width:<?php echo (int) $s['sidebar_width']; ?>px;
                    height:100vh;
                    max-height:<?php echo esc_attr($s['sidebar_max_height']); ?>;
                    background:<?php echo esc_attr($s['sidebar_bg']); ?>;
                    border-radius:0 <?php echo (int) $s['sidebar_border_radius']; ?>px <?php echo (int) $s['sidebar_border_radius']; ?>px 0;
                    box-shadow:<?php echo esc_attr($s['sidebar_shadow']); ?>;
                    z-index:10000;
                    transform:translateX(-100%);
                    transition:transform 0.3s ease;
                    <?php echo esc_attr( $panel_flex ); ?>">
            <?php if ($header_sticky) : ?>
            <!-- Cabecera fija: fuera del scroll, siempre visible -->
            <div class="etn-egr-sidebar-header etn-egr-sidebar-header-fixed" style="flex-shrink:0;padding:<?php echo absint( $pad ); ?>px;background:<?php echo esc_attr($s['sidebar_bg']); ?>;">
                <div class="etn-egr-sidebar-header-inner">
                    <h2 class="etn-egr-sidebar-title">
                        <?php echo esc_html__('Google reviews', 'etchenet-reviews-for-google-business'); ?>
                    </h2>
                    <div class="etn-egr-sidebar-rating">
                        <div class="etn-egr-b-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:18px;">
                            ★★★★★
                        </div>
                        <span class="etn-egr-sidebar-rating-text">
                            <strong><?php echo esc_html(number_format_i18n($rating, 1)); ?></strong> / 5.0
                            (<?php echo (int) $total; ?> <?php echo esc_html(_n('review', 'reviews', $total, 'etchenet-reviews-for-google-business')); ?>)
                        </span>
                    </div>
                    <?php if ($write_review_url) : ?>
                        <p style="margin:10px 0 0 0;font-size:13px;">
                            <a href="<?php echo esc_url( $write_review_url ); ?>" target="_blank" rel="noopener noreferrer" style="color:<?php echo esc_attr($s['c_name']); ?>;text-decoration:underline;"><?php echo esc_html__('Write a review', 'etchenet-reviews-for-google-business'); ?></a>
                        </p>
                    <?php endif; ?>
                </div>
                <button type="button" class="etn-egr-sidebar-close" aria-label="<?php echo esc_attr__('Close', 'etchenet-reviews-for-google-business'); ?>">&times;</button>
            </div>
            <?php endif; ?>
            <div class="etn-egr-sidebar-panel-scroll" 
                 style="<?php echo esc_attr( $scroll_flex ); ?>
                        overflow-y:auto;
                        overflow-x:hidden;
                        padding:<?php echo (int) $s['sidebar_padding']; ?>px;
                        <?php if ($header_sticky) { echo 'padding-top:0;'; } ?>">
            <?php if (!$header_sticky) : ?>
            <!-- Cabecera dentro del scroll (cuando no está activada la opción fija) -->
            <div class="etn-egr-sidebar-header">
                <div class="etn-egr-sidebar-header-inner">
                    <h2 class="etn-egr-sidebar-title">
                        <?php echo esc_html__('Google reviews', 'etchenet-reviews-for-google-business'); ?>
                    </h2>
                    <div class="etn-egr-sidebar-rating">
                        <div class="etn-egr-b-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:18px;">
                            ★★★★★
                        </div>
                        <span class="etn-egr-sidebar-rating-text">
                            <strong><?php echo esc_html(number_format_i18n($rating, 1)); ?></strong> / 5.0
                            (<?php echo (int) $total; ?> <?php echo esc_html(_n('review', 'reviews', $total, 'etchenet-reviews-for-google-business')); ?>)
                        </span>
                    </div>
                    <?php if ($write_review_url) : ?>
                        <p style="margin:10px 0 0 0;font-size:13px;">
                            <a href="<?php echo esc_url( $write_review_url ); ?>" target="_blank" rel="noopener noreferrer" style="color:<?php echo esc_attr($s['c_name']); ?>;text-decoration:underline;"><?php echo esc_html__('Write a review', 'etchenet-reviews-for-google-business'); ?></a>
                        </p>
                    <?php endif; ?>
                </div>
                <button type="button" class="etn-egr-sidebar-close" aria-label="<?php echo esc_attr__('Close', 'etchenet-reviews-for-google-business'); ?>">&times;</button>
            </div>
            <?php endif; ?>
            <!-- Lista de reseñas apiladas -->
            <div class="etn-egr-sidebar-reviews" style="padding-top:0;">
                <?php foreach ($panel_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);
                    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;
                    }
                    ?>
                    <div class="etn-egr-sidebar-review-card"
                         style="background:<?php echo esc_attr($s['sidebar_card_bg']); ?>;
                                padding:<?php echo (int) $s['sidebar_card_padding']; ?>px;
                                margin-bottom:<?php echo (int) $s['sidebar_card_margin']; ?>px;
                                border-radius:<?php echo (int) $s['sidebar_card_border_radius']; ?>px;
                                box-shadow:0 2px 8px rgba(0,0,0,0.1);">
                        
                        <!-- Autor -->
                        <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
                            <?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"
                                     style="width:40px;height:40px;border-radius:50%;object-fit:cover;">
                            <?php endif; ?>
                            <div style="flex:1;">
                                <div style="font-weight:bold;color:<?php echo esc_attr($s['c_name']); ?>;font-size:14px;">
                                    <?php echo esc_html($r['author_name'] ?? ''); ?>
                                </div>
                                <div class="etn-egr-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:14px;margin-top:4px;">
                                    <?php
                                    $rev_rating = isset($r['rating']) ? (int) $r['rating'] : 0;
                                    for ($i = 0; $i < $rev_rating; $i++) {
                                        echo '<span class="etn-egr-star">★</span>';
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>

                        <!-- Texto del extracto -->
                        <p style="color:<?php echo esc_attr($s['c_text']); ?>;font-size:13px;line-height:1.6;margin:0 0 8px 0;">
                            <?php echo esc_html($display_text); ?>
                            <?php if ($needs_read_more) : ?>...<?php endif; ?>
                        </p>

                        <!-- Botón "Leer más" separado -->
                        <?php if ($needs_read_more) : ?>
                            <div style="margin-top:8px;">
                                <a href="#" class="etn-egr-read-more etn-egr-read-more-sidebar" 
                                   data-full-text-b64="<?php echo esc_attr(base64_encode($full_text)); ?>"
                                   style="display:inline-block;color:<?php echo esc_attr($s['c_name']); ?>;text-decoration:underline;cursor:pointer;font-size:13px;font-weight:500;">
                                    <?php echo esc_html__('Read more', 'etchenet-reviews-for-google-business'); ?>
                                </a>
                            </div>
                        <?php endif; ?>

                        <!-- Fecha si está disponible -->
                        <?php if (!empty($r['relative_time_description'])) : ?>
                            <div style="margin-top:8px;font-size:11px;color:#999;">
                                <?php echo esc_html($r['relative_time_description']); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            </div>
        </div>
        <?php
    }
}

