<?php

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

class ETN_EGR_Admin {

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

    public function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('wp_ajax_etn_egr_sync_reviews', [$this, 'sync_reviews_handler']);
        add_action('wp_ajax_etn_egr_add_manual_review', [$this, 'ajax_add_manual_review']);
        add_action('wp_ajax_etn_egr_update_manual_review', [$this, 'ajax_update_manual_review']);
        add_action('wp_ajax_etn_egr_delete_manual_review', [$this, 'ajax_delete_manual_review']);
        add_action('wp_ajax_etn_egr_bulk_delete_manual_reviews', [$this, 'ajax_bulk_delete_manual_reviews']);
        add_action('wp_ajax_etn_egr_save_reviews_order', [$this, 'ajax_save_reviews_order']);
        add_action('wp_ajax_etn_egr_set_review_visibility', [$this, 'ajax_set_review_visibility']);
        add_action('wp_ajax_etn_egr_reset_google_reviews', [$this, 'ajax_reset_google_reviews']);
        add_action('admin_post_etn_egr_import_reviews', [$this, 'handle_import_reviews']);
        add_action('admin_post_etn_egr_export_reviews', [$this, 'handle_export_reviews']);
        // Hook para sincronización automática vía WP‑Cron
        add_action('etn_egr_daily_sync', [$this, 'cron_sync_reviews']);
    }

    public function add_admin_menu() {
        add_menu_page(
            __('Etchenet Reviews for Google Business', 'etchenet-reviews-for-google-business'),
            __('Etchenet Reviews', 'etchenet-reviews-for-google-business'),
            'manage_options',
            'etn-egr-reviews',
            [$this, 'admin_page'],
            'dashicons-star-filled'
        );
    }

    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'toplevel_page_etn-egr-reviews') {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_script(
            'wp-color-picker-alpha',
            ETN_EGR_PLUGIN_URL . 'assets/js/wp-color-picker-alpha.min.js',
            ['jquery', 'wp-color-picker'],
            '3.0.4',
            true
        );
        wp_add_inline_script(
            'wp-color-picker-alpha',
            'jQuery(function($){ if($.fn.wpColorPicker){ $(".etn-egr-color-input").wpColorPicker({ type: "full" }); }});',
            'after'
        );
        wp_enqueue_script(
            'etn-egr-admin-reviews-order',
            ETN_EGR_PLUGIN_URL . 'assets/js/admin-reviews-order.js',
            ['jquery', 'jquery-ui-sortable'],
            '1.1',
            true
        );
        wp_localize_script('etn-egr-admin-reviews-order', 'etnEgrAdmin', [
            'nonce' => wp_create_nonce('etn_egr_manual_review'),
            'saveOrderSuccess' => __('Order saved. It applies to the carousel and side panel.', 'etchenet-reviews-for-google-business'),
            'saveOrderError'   => __('Error', 'etchenet-reviews-for-google-business'),
            'saveOrderConn'   => __('Connection error.', 'etchenet-reviews-for-google-business'),
        ]);

        wp_enqueue_style(
            'etn-egr-admin',
            ETN_EGR_PLUGIN_URL . 'assets/css/admin.css',
            [],
            '2.2'
        );

        $etn_egr_manual_nonce = wp_create_nonce('etn_egr_manual_review');
        $etn_egr_l10n = [
            'syncing'     => __('Syncing...', 'etchenet-reviews-for-google-business'),
            'syncError'   => __('Unknown error while syncing.', 'etchenet-reviews-for-google-business'),
            'required'    => __('Author name and review text are required.', 'etchenet-reviews-for-google-business'),
            'adding'      => __('Adding...', 'etchenet-reviews-for-google-business'),
            'addReview'   => __('Add review', 'etchenet-reviews-for-google-business'),
            'errorAdd'    => __('Could not add review.', 'etchenet-reviews-for-google-business'),
            'errorConn'   => __('Connection error.', 'etchenet-reviews-for-google-business'),
            'confirmDel'  => __('Delete this manual review?', 'etchenet-reviews-for-google-business'),
            'confirmBulk' => __('Delete the selected reviews?', 'etchenet-reviews-for-google-business'),
            'errorDel'    => __('Could not delete.', 'etchenet-reviews-for-google-business'),
            'noSelected'  => __('Select at least one manual review.', 'etchenet-reviews-for-google-business'),
            'saving'      => __('Saving...', 'etchenet-reviews-for-google-business'),
            'saved'       => __('Review updated successfully.', 'etchenet-reviews-for-google-business'),
            'errorUpdate' => __('Could not update.', 'etchenet-reviews-for-google-business'),
            'saveBtn'     => __('Save changes', 'etchenet-reviews-for-google-business'),
            'confirmReset'  => __('Delete ALL stored Google reviews? Manual reviews will not be affected. You can sync again right after.', 'etchenet-reviews-for-google-business'),
            'resetting'     => __('Deleting...', 'etchenet-reviews-for-google-business'),
            'resetBtn'      => __('Delete Google reviews and re-sync', 'etchenet-reviews-for-google-business'),
            'resetError'    => __('Could not delete Google reviews.', 'etchenet-reviews-for-google-business'),
        ];

        wp_enqueue_script(
            'etn-egr-admin-ui',
            ETN_EGR_PLUGIN_URL . 'assets/js/admin-ui.js',
            ['jquery', 'etn-egr-admin-reviews-order'],
            '2.2',
            true
        );

        wp_localize_script(
            'etn-egr-admin-ui',
            'etnEgrAdminUi',
            [
                'manualNonce' => $etn_egr_manual_nonce,
                'l10n'        => $etn_egr_l10n,
            ]
        );
    }

    public function register_settings() {
        register_setting('etn_egr_settings', 'etn_egr_api_key', [
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        register_setting('etn_egr_settings', 'etn_egr_place_id', [
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        register_setting('etn_egr_settings', 'etn_egr_enable_cron', [
            'sanitize_callback' => function ( $v ) {
                return absint( $v ) ? 1 : 0;
            },
        ]);
        register_setting('etn_egr_settings', $this->opt_styles, [
            'sanitize_callback' => [$this, 'sanitize_style_options'],
        ]);
    }

    private function sanitize_rgba_or_hex($value, $fallback) {
        $value = sanitize_text_field((string) $value);
        $hex = sanitize_hex_color($value);
        if ($hex) {
            return $hex;
        }
        if (preg_match('/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*(0|1|0?\.\d+))?\s*\)$/', $value)) {
            return $value;
        }
        return $fallback;
    }

    public function sanitize_style_options($value) {
        $defaults = etn_egr_get_default_styles();
        $submitted = is_array($value) ? $value : [];
        $clean = $defaults;

        $bool_keys = [
            'equal_height', 'autoplay', 'arrows', 'arrows_circle', 'dots',
            'exclude_empty', 'show_avatar', 'show_date', 'show_google_logo',
            'show_read_more', 'show_badge', 'rich_snippets', 'sidebar_header_sticky',
        ];
        foreach ($bool_keys as $key) {
            $clean[$key] = !empty($submitted[$key]) ? 1 : 0;
        }

        $int_rules = [
            'columns' => [1, 6],
            'max_reviews' => [1, 9999],
            'card_padding' => [8, 48],
            'card_gap' => [0, 40],
            'card_read_more_gap' => [0, 24],
            'excerpt_length' => [50, 500],
            'speed' => [500, 20000],
            'arrow_size' => [24, 80],
            'border_radius' => [0, 50],
            'font_size' => [10, 48],
            'badge_m_side' => [0, 300],
            'badge_m_bottom' => [0, 300],
            'badge_padding' => [0, 60],
            'min_stars' => [1, 5],
            'sidebar_width' => [240, 1200],
            'sidebar_padding' => [0, 60],
            'sidebar_border_radius' => [0, 60],
            'sidebar_card_padding' => [0, 60],
            'sidebar_card_margin' => [0, 80],
            'sidebar_card_border_radius' => [0, 60],
            'sidebar_max_reviews' => [0, 9999],
        ];
        foreach ($int_rules as $key => $range) {
            if (isset($submitted[$key])) {
                $n = absint($submitted[$key]);
                $clean[$key] = max($range[0], min($range[1], $n));
            }
        }

        $enum_rules = [
            'card_aspect_ratio' => ['16_9', '4_3', 'auto'],
            'arrow_pos_h' => ['limit', 'exterior', 'interior'],
            'arrow_pos_v' => ['top', 'middle', 'bottom'],
            'badge_pos' => ['left', 'right'],
            'reviews_order' => ['date_desc', 'date_asc', 'rating_desc', 'rating_asc', 'manual'],
        ];
        foreach ($enum_rules as $key => $allowed) {
            if (isset($submitted[$key])) {
                $val = sanitize_text_field((string) $submitted[$key]);
                $clean[$key] = in_array($val, $allowed, true) ? $val : $defaults[$key];
            }
        }

        $rgba_or_hex_keys = ['bg_card', 'c_name', 'c_text', 'c_star', 'sidebar_bg', 'sidebar_card_bg', 'arrow_bg_color', 'arrow_icon_color'];
        foreach ($rgba_or_hex_keys as $key) {
            if (isset($submitted[$key])) {
                $clean[$key] = $this->sanitize_rgba_or_hex($submitted[$key], $defaults[$key]);
            }
        }

        if (isset($submitted['write_review_url'])) {
            $clean['write_review_url'] = esc_url_raw($submitted['write_review_url']);
        }
        if (isset($submitted['sidebar_max_height'])) {
            $max_h = sanitize_text_field((string) $submitted['sidebar_max_height']);
            $clean['sidebar_max_height'] = preg_match('/^\d+(px|vh|vw|%)$/', $max_h) ? $max_h : $defaults['sidebar_max_height'];
        }
        if (isset($submitted['sidebar_shadow'])) {
            $shadow = sanitize_text_field((string) $submitted['sidebar_shadow']);
            $clean['sidebar_shadow'] = preg_match('/^[0-9a-zA-Z\.\,\-\(\)\s%#]+$/', $shadow) ? $shadow : $defaults['sidebar_shadow'];
        }

        return $clean;
    }

    /**
     * Sincronización lanzada desde el botón AJAX en el admin.
     */
    public function sync_reviews_handler() {
        $result = $this->run_sync();

        if ($result['success']) {
            wp_send_json_success($result['message']);
        }

        wp_send_json_error($result['message']);
    }

    /**
     * AJAX: supprime toutes les reviews Google stockées (garde les manuelles)
     * et purge les transients de cache API pour permettre une re-sync propre.
     */
    public function ajax_reset_google_reviews() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }

        $data = get_option($this->opt_data, []);
        $old_count = is_array($data) && !empty($data['reviews']) ? count($data['reviews']) : 0;

        if (is_array($data)) {
            $data['reviews'] = [];
            update_option($this->opt_data, $data);
        }

        $api_key  = trim((string) get_option('etn_egr_api_key', ''));
        $place_id = trim((string) get_option('etn_egr_place_id', ''));
        if ($api_key !== '' && $place_id !== '') {
            delete_transient('etn_egr_api_' . md5($place_id . $api_key . 'most_relevant'));
            delete_transient('etn_egr_api_' . md5($place_id . $api_key . 'newest'));
        }

        wp_send_json_success(
            sprintf(
                /* translators: %d: number of Google reviews deleted */
                __('%d Google review(s) deleted. You can sync again.', 'etchenet-reviews-for-google-business'),
                $old_count
            )
        );
    }

    /**
     * Sincronización silenciosa para WP-Cron (cada 24h).
     */
    public function cron_sync_reviews() {
        // Permitir desactivar la sincronización automática desde el panel.
        $enabled = get_option('etn_egr_enable_cron', 1);
        if ((int) $enabled !== 1) {
            return;
        }
        // No mostramos mensajes al usuario; solo ejecutamos la lógica.
        $this->run_sync();
    }

    /**
     * Núcleo de sincronización: lee reseñas existentes, pide las nuevas
     * (dos llamadas: "most_relevant" + "newest" para maximizar la captación),
     * combina sin duplicados y cachea avatares localmente.
     *
     * @return array{success:bool,message:string}
     */
    private function run_sync() {
        $api_key  = trim((string) get_option('etn_egr_api_key', get_option('grp_api_key', '')));
        $place_id = trim((string) get_option('etn_egr_place_id', get_option('grp_place_id', '')));

        if (empty($api_key) || empty($place_id)) {
            return [
                'success' => false,
                'message' => __('You must set API Key and Place ID before syncing.', 'etchenet-reviews-for-google-business'),
            ];
        }

        $existing_data    = get_option($this->opt_data);
        $existing_reviews = [];
        $existing_ids     = [];

        if ($existing_data && !empty($existing_data['reviews']) && is_array($existing_data['reviews'])) {
            $existing_reviews = $existing_data['reviews'];
            foreach ($existing_reviews as $review) {
                $existing_ids[] = $this->etn_egr_review_uid($review);
            }
        }

        $etn_egr_lang = substr(get_locale(), 0, 2);
        $base_url = sprintf(
            'https://maps.googleapis.com/maps/api/place/details/json?place_id=%s&fields=reviews,rating,user_ratings_total,name&key=%s&language=%s',
            rawurlencode($place_id),
            rawurlencode($api_key),
            rawurlencode($etn_egr_lang)
        );

        $sort_modes = ['most_relevant', 'newest'];
        $all_google_reviews = [];
        $metadata           = [];
        $last_error         = '';

        foreach ($sort_modes as $sort) {
            $cache_key = 'etn_egr_api_' . md5($place_id . $api_key . $sort);
            $body      = get_transient($cache_key);

            if (false === $body || !is_array($body)) {
                $url = $base_url;
                if ('newest' === $sort) {
                    $url .= '&reviews_sort=newest';
                }

                $response = wp_remote_get($url, ['timeout' => 30]);

                if (is_wp_error($response)) {
                    $last_error = __('Could not connect to Google. Check your server or firewall.', 'etchenet-reviews-for-google-business');
                    continue;
                }

                $body = json_decode(wp_remote_retrieve_body($response), true);
                if (is_array($body) && !empty($body['status']) && 'OK' === $body['status']) {
                    set_transient($cache_key, $body, 12 * HOUR_IN_SECONDS);
                }
            }

            if (!is_array($body)) {
                continue;
            }

            if (!empty($body['status']) && 'OK' !== $body['status']) {
                if ('REQUEST_DENIED' === $body['status']) {
                    $last_error = __("REQUEST_DENIED: Your API key is being rejected.\n\nRecommended steps in Google Cloud:\n1. Go to Google Cloud Console → APIs & Services → Credentials.\n2. Click your API key.\n3. Under Key restrictions, remove HTTP referrer (web sites) restrictions or add your site's exact domain (including protocol and subdomain).\n4. Save and wait a few minutes before trying again.", 'etchenet-reviews-for-google-business');
                } else {
                    $last_error = __('Google says:', 'etchenet-reviews-for-google-business') . ' ' . ($body['error_message'] ?? $body['status']);
                }
                continue;
            }

            if (empty($metadata) && isset($body['result'])) {
                $metadata = $body['result'];
            }

            if (!empty($body['result']['reviews']) && is_array($body['result']['reviews'])) {
                foreach ($body['result']['reviews'] as $review) {
                    $uid = $this->etn_egr_review_uid($review);
                    $all_google_reviews[$uid] = $review;
                }
            }
        }

        if (empty($all_google_reviews) && empty($existing_reviews)) {
            $msg = $last_error !== ''
                ? $last_error
                : __('No Google reviews were returned. Check your API configuration.', 'etchenet-reviews-for-google-business');
            return ['success' => false, 'message' => $msg];
        }

        $reviews_to_add = [];

        foreach ($all_google_reviews as $uid => $new_review) {
            if (in_array($uid, $existing_ids, true)) {
                continue;
            }

            if (!empty($new_review['profile_photo_url'])) {
                $cached = $this->cache_profile_photo($new_review['profile_photo_url'], $new_review['author_name'] ?? '');
                if ($cached) {
                    $new_review['profile_photo_url'] = $cached;
                }
            }
            $new_review['visible'] = true;
            $reviews_to_add[] = $new_review;
        }

        $merged_reviews = array_merge($reviews_to_add, $existing_reviews);

        $updated_data = [
            'reviews'            => $merged_reviews,
            'rating'             => $metadata['rating'] ?? ($existing_data['rating'] ?? 0),
            'user_ratings_total' => $metadata['user_ratings_total'] ?? ($existing_data['user_ratings_total'] ?? 0),
            'name'               => $metadata['name'] ?? ($existing_data['name'] ?? ''),
        ];

        update_option($this->opt_data, $updated_data);

        $added_count = count($reviews_to_add);
        $total_count = count($merged_reviews);

        if ($added_count > 0) {
            return [
                'success' => true,
                'message' => sprintf(
                    /* translators: 1: number of new reviews added, 2: total number of reviews */
                    __('Sync complete. Added %1$d new review(s). Total: %2$d reviews.', 'etchenet-reviews-for-google-business'),
                    $added_count,
                    $total_count
                ),
            ];
        }

        return [
            'success' => true,
            'message' => sprintf(
                /* translators: %d: total number of saved reviews */
                __('Sync complete. No new reviews. Total: %d reviews stored.', 'etchenet-reviews-for-google-business'),
                $total_count
            ),
        ];
    }

    /**
     * Genera un identificador único para una reseña de Google basado en
     * su timestamp o, como fallback, un hash de autor + texto.
     *
     * @param array $review Datos de una reseña.
     * @return int|string UID de la reseña.
     */
    private function etn_egr_review_uid( $review ) {
        if ( ! empty( $review['time'] ) ) {
            return (int) $review['time'];
        }
        $text_preview = substr( $review['text'] ?? '', 0, 50 );
        return md5( ( $review['author_name'] ?? '' ) . $text_preview );
    }

    /**
     * Descarga la imagen de perfil de Google y la guarda en uploads/etn-egr-avatars.
     * Devuelve la URL local o false si falla (en cuyo caso se mantiene la original).
     *
     * @param string $url
     * @param string $author_name
     * @return string|false
     */
    private function cache_profile_photo($url, $author_name = '') {
        if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
            return false;
        }

        $upload_dir = wp_upload_dir();
        if (!empty($upload_dir['error'])) {
            return false;
        }

        $avatars_dir = trailingslashit($upload_dir['basedir']) . 'etn-egr-avatars/';
        if (!wp_mkdir_p($avatars_dir)) {
            return false;
        }

        $parsed    = wp_parse_url($url);
        $path      = isset($parsed['path']) ? $parsed['path'] : '';
        $ext       = pathinfo($path, PATHINFO_EXTENSION);
        $ext       = $ext ?: 'jpg';
        $slug_name = sanitize_title($author_name ?: 'avatar');
        $filename  = 'avatar-' . $slug_name . '-' . md5($url) . '.' . $ext;
        $filepath  = $avatars_dir . $filename;

        // Ya existe cacheada
        if (file_exists($filepath)) {
            return trailingslashit($upload_dir['baseurl']) . 'etn-egr-avatars/' . $filename;
        }

        $response = wp_remote_get($url, ['timeout' => 20]);
        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code !== 200) {
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        if (empty($body)) {
            return false;
        }

        if (file_put_contents($filepath, $body) === false) {
            return false;
        }

        return trailingslashit($upload_dir['baseurl']) . 'etn-egr-avatars/' . $filename;
    }

    /**
     * Añadir reseña manual (AJAX).
     */
    public function ajax_add_manual_review() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $author = isset($_POST['author_name']) ? sanitize_text_field(wp_unslash($_POST['author_name'])) : '';
        $text   = isset($_POST['text']) ? sanitize_textarea_field(wp_unslash($_POST['text'])) : '';
        $rating = isset($_POST['rating']) ? (int) $_POST['rating'] : 5;
        $photo_id = isset($_POST['profile_photo_id']) ? (int) $_POST['profile_photo_id'] : 0;
        $photo    = '';
        if ($photo_id > 0 && function_exists('wp_get_attachment_image_url')) {
            $photo = wp_get_attachment_image_url($photo_id, 'thumbnail');
            if (!is_string($photo)) {
                $photo = '';
            }
        }
        if ($photo === '' && isset($_POST['profile_photo_url'])) {
            $photo = esc_url_raw(wp_unslash($_POST['profile_photo_url']));
        }
        $date   = isset($_POST['relative_time_description']) ? sanitize_text_field(wp_unslash($_POST['relative_time_description'])) : '';

        if ($author === '' || $text === '') {
            wp_send_json_error(__('Author name and review text are required.', 'etchenet-reviews-for-google-business'));
        }
        $rating = max(1, min(5, $rating));

        $list = get_option($this->opt_manual, []);
        if (!is_array($list)) {
            $list = [];
        }
        $id = 'etn_egr_manual_' . wp_generate_password(8, false);
        $item = [
            'id'                      => $id,
            'author_name'              => $author,
            'text'                     => $text,
            'rating'                   => $rating,
            'profile_photo_url'        => $photo,
            'relative_time_description' => $date,
            'time'                     => time(),
            'visible'                  => true,
        ];
        if ($photo_id > 0) {
            $item['profile_photo_id'] = $photo_id;
        }
        $list[] = $item;
        update_option($this->opt_manual, $list);
        wp_cache_delete($this->opt_manual, 'options');
        wp_send_json_success(['id' => $id, 'message' => __('Review added successfully.', 'etchenet-reviews-for-google-business')]);
    }

    /**
     * Eliminar reseña manual (AJAX).
     */
    public function ajax_delete_manual_review() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $id = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : '';
        if ($id === '') {
            wp_send_json_error(__('Invalid ID.', 'etchenet-reviews-for-google-business'));
        }
        $list = get_option($this->opt_manual, []);
        if (!is_array($list)) {
            $list = [];
        }
        $list = array_values(array_filter($list, function ($r) use ($id) {
            return (isset($r['id']) ? $r['id'] : '') !== $id;
        }));
        update_option($this->opt_manual, $list);
        wp_cache_delete($this->opt_manual, 'options');
        wp_send_json_success(__('Review deleted.', 'etchenet-reviews-for-google-business'));
    }

    /**
     * Eliminar varias reseñas manuales a la vez (AJAX).
     */
    public function ajax_bulk_delete_manual_reviews() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $ids = isset($_POST['ids']) && is_array($_POST['ids']) ? array_map('sanitize_text_field', wp_unslash($_POST['ids'])) : [];
        $ids = array_filter($ids);
        if (empty($ids)) {
            wp_send_json_error(__('No reviews selected.', 'etchenet-reviews-for-google-business'));
        }
        $list = get_option($this->opt_manual, []);
        if (!is_array($list)) {
            $list = [];
        }
        $ids_set = array_flip($ids);
        $list = array_values(array_filter($list, function ($r) use ($ids_set) {
            $id = isset($r['id']) ? $r['id'] : '';
            return $id === '' || !isset($ids_set[$id]);
        }));
        update_option($this->opt_manual, $list);
        wp_cache_delete($this->opt_manual, 'options');
        wp_send_json_success(sprintf(
            /* translators: %d: number of reviews deleted (singular: one review, plural: multiple reviews) */
            _n('%d review deleted.', '%d reviews deleted.', count($ids), 'etchenet-reviews-for-google-business'),
            count($ids)
        ));
    }

    /**
     * Actualizar reseña manual (AJAX).
     */
    public function ajax_update_manual_review() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $id     = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : '';
        $author = isset($_POST['author_name']) ? sanitize_text_field(wp_unslash($_POST['author_name'])) : '';
        $text   = isset($_POST['text']) ? sanitize_textarea_field(wp_unslash($_POST['text'])) : '';
        $rating = isset($_POST['rating']) ? (int) $_POST['rating'] : 5;
        $photo_id = isset($_POST['profile_photo_id']) ? (int) $_POST['profile_photo_id'] : 0;
        $photo    = '';
        if ($photo_id > 0 && function_exists('wp_get_attachment_image_url')) {
            $photo = wp_get_attachment_image_url($photo_id, 'thumbnail');
            if (!is_string($photo)) {
                $photo = '';
            }
        }
        if ($photo === '' && isset($_POST['profile_photo_url'])) {
            $photo = esc_url_raw(wp_unslash($_POST['profile_photo_url']));
        }
        $date    = isset($_POST['relative_time_description']) ? sanitize_text_field(wp_unslash($_POST['relative_time_description'])) : '';
        $visible = isset($_POST['visible']) ? (int) $_POST['visible'] : 1;

        if ($id === '') {
            wp_send_json_error(__('Invalid ID.', 'etchenet-reviews-for-google-business'));
        }
        if ($author === '' || $text === '') {
            wp_send_json_error(__('Author name and review text are required.', 'etchenet-reviews-for-google-business'));
        }
        $rating = max(1, min(5, $rating));

        $list = get_option($this->opt_manual, []);
        if (!is_array($list)) {
            $list = [];
        }
        $found = false;
        foreach ($list as $i => $r) {
            if ((isset($r['id']) ? $r['id'] : '') === $id) {
                $list[$i]['author_name']               = $author;
                $list[$i]['text']                     = $text;
                $list[$i]['rating']                    = $rating;
                $list[$i]['profile_photo_url']        = $photo;
                if ($photo_id > 0) {
                    $list[$i]['profile_photo_id']     = $photo_id;
                } else {
                    unset($list[$i]['profile_photo_id']);
                }
                $list[$i]['relative_time_description'] = $date;
                $list[$i]['visible']                   = (bool) $visible;
                $found = true;
                break;
            }
        }
        if (!$found) {
            wp_send_json_error(__('Review not found.', 'etchenet-reviews-for-google-business'));
        }
        update_option($this->opt_manual, $list);
        wp_cache_delete($this->opt_manual, 'options');
        wp_send_json_success(__('Review updated successfully.', 'etchenet-reviews-for-google-business'));
    }

    /**
     * Cambiar visibilidad de una reseña (manual o de Google) en el front (AJAX).
     */
    public function ajax_set_review_visibility() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $etn_egr_key = isset($_POST['etn_egr_key']) ? sanitize_text_field(wp_unslash($_POST['etn_egr_key'])) : '';
        $visible = isset($_POST['visible']) ? (int) $_POST['visible'] : 1;
        if ($etn_egr_key === '') {
            wp_send_json_error(__('Invalid review identifier.', 'etchenet-reviews-for-google-business'));
        }

        if (strpos($etn_egr_key, 'g_') === 0) {
            $data = get_option($this->opt_data, []);
            if (!is_array($data) || empty($data['reviews']) || !is_array($data['reviews'])) {
            wp_send_json_error(__('Review not found.', 'etchenet-reviews-for-google-business'));
            }
            $found = false;
            foreach ($data['reviews'] as $i => $r) {
                $key = 'g_' . (isset($r['time']) ? (int) $r['time'] : 0);
                if ($key === $etn_egr_key) {
                    $data['reviews'][$i]['visible'] = (bool) $visible;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
            wp_send_json_error(__('Review not found.', 'etchenet-reviews-for-google-business'));
            }
            update_option($this->opt_data, $data);
            wp_cache_delete($this->opt_data, 'options');
        } else {
            $list = get_option($this->opt_manual, []);
            if (!is_array($list)) {
                $list = [];
            }
            $found = false;
            foreach ($list as $i => $r) {
                if ((isset($r['id']) ? $r['id'] : '') === $etn_egr_key) {
                    $list[$i]['visible'] = (bool) $visible;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                wp_send_json_error(__('Review not found.', 'etchenet-reviews-for-google-business'));
            }
            update_option($this->opt_manual, $list);
            wp_cache_delete($this->opt_manual, 'options');
        }

        wp_send_json_success(__('Visibility updated.', 'etchenet-reviews-for-google-business'));
    }

    /**
     * Guardar orden manual de reseñas (AJAX).
     */
    public function ajax_save_reviews_order() {
        check_ajax_referer('etn_egr_manual_review', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        $order = isset($_POST['order']) && is_array($_POST['order']) ? array_map('sanitize_text_field', wp_unslash($_POST['order'])) : [];
        update_option(ETN_EGR_OPTION_REVIEWS_ORDER, $order);
        // Activar orden manual en estilos para que se aplique en carrusel y panel
        $styles = get_option($this->opt_styles, etn_egr_get_default_styles());
        if (!is_array($styles)) {
            $styles = etn_egr_get_default_styles();
        }
        $styles['reviews_order'] = 'manual';
        update_option($this->opt_styles, $styles);
        wp_send_json_success(__('Order saved.', 'etchenet-reviews-for-google-business'));
    }

    /**
     * Importar reseñas desde archivo Excel (.xlsx) o CSV.
     */
    public function handle_import_reviews() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        check_admin_referer('etn_egr_import_reviews');
        $tmp_name = isset($_FILES['etn_egr_import_file']['tmp_name']) ? sanitize_text_field(wp_unslash($_FILES['etn_egr_import_file']['tmp_name'])) : '';
        if (empty($tmp_name) || !is_uploaded_file($tmp_name)) {
            wp_safe_redirect(add_query_arg([
                'etn_egr_import' => 'error_empty',
                '_wpnonce'   => wp_create_nonce('etn_egr_import_result'),
            ], wp_get_referer()));
            exit;
        }
        $filename = isset($_FILES['etn_egr_import_file']['name']) ? sanitize_file_name(wp_unslash($_FILES['etn_egr_import_file']['name'])) : '';
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (!in_array($ext, ['csv', 'xlsx'], true)) {
            wp_safe_redirect(add_query_arg([
                'etn_egr_import' => 'error_format',
                '_wpnonce'   => wp_create_nonce('etn_egr_import_result'),
            ], wp_get_referer()));
            exit;
        }
        require_once ETN_EGR_PLUGIN_DIR . 'includes/class-egr-import.php';
        $parsed = ETN_EGR_Import::parse_file($tmp_name, $filename);
        $reviews = ETN_EGR_Import::rows_to_reviews($parsed['headers'], $parsed['rows']);
        if (empty($reviews)) {
            wp_safe_redirect(add_query_arg([
                'etn_egr_import' => 'error_no_data',
                '_wpnonce'   => wp_create_nonce('etn_egr_import_result'),
            ], wp_get_referer()));
            exit;
        }
        $list = get_option($this->opt_manual, []);
        if (!is_array($list)) {
            $list = [];
        }
        foreach ($reviews as $r) {
            $list[] = [
                'id'                      => 'etn_egr_manual_' . wp_generate_password(8, false),
                'author_name'              => $r['author_name'],
                'text'                     => $r['text'],
                'rating'                   => $r['rating'],
                'profile_photo_url'        => $r['profile_photo_url'],
                'relative_time_description' => $r['relative_time_description'],
                'time'                     => time(),
                'visible'                  => true,
            ];
        }
        update_option($this->opt_manual, $list);
        wp_cache_delete($this->opt_manual, 'options');
        wp_safe_redirect(add_query_arg([
            'etn_egr_import' => count($reviews),
            '_wpnonce'   => wp_create_nonce('etn_egr_import_result'),
        ], wp_get_referer()));
        exit;
    }

    /**
     * Format one CSV line (fields joined by delimiter, quoted as needed).
     *
     * @param array  $row   Row fields.
     * @param string $delim Delimiter.
     * @return string
     */
    private function etn_egr_csv_line(array $row, $delim = ';') {
        $out = [];
        foreach ($row as $cell) {
            $cell = (string) $cell;
            if (strpos($cell, '"') !== false || strpos($cell, $delim) !== false || strpos($cell, "\n") !== false) {
                $cell = '"' . str_replace('"', '""', $cell) . '"';
            }
            $out[] = $cell;
        }
        return implode($delim, $out) . "\n";
    }

    /**
     * Exportar todas las reseñas (manuales + Google) a CSV.
     */
    public function handle_export_reviews() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied.', 'etchenet-reviews-for-google-business'));
        }
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'etn_egr_export_reviews')) {
            wp_die(esc_html__('Invalid link.', 'etchenet-reviews-for-google-business'));
        }
        $reviews = etn_egr_get_all_reviews();
        $filename = 'etchenet-reviews-' . gmdate('Y-m-d-His') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . sanitize_file_name($filename) . '"');
        $buffer = "\xEF\xBB\xBF"; // UTF-8 BOM
        $buffer .= $this->etn_egr_csv_line(['Autor', 'Texto', 'Estrellas', 'Fecha', 'URL foto', 'Origen'], ';');
        foreach ($reviews as $r) {
            $origin = (isset($r['id']) && $r['id'] !== '' && strpos((string) $r['id'], 'etn_egr_manual_') === 0) ? 'Manual' : 'Google';
            $buffer .= $this->etn_egr_csv_line([
                $r['author_name'] ?? '',
                $r['text'] ?? '',
                (int) ($r['rating'] ?? 0),
                $r['relative_time_description'] ?? '',
                $r['profile_photo_url'] ?? '',
                $origin,
            ], ';');
        }
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV download, not HTML; buffer built from etn_egr_csv_line().
        echo $buffer;
        exit;
    }

    public function admin_page() {
        $s    = get_option($this->opt_styles, etn_egr_get_default_styles());
        $data = get_option($this->opt_data);

        $import_msg = '';
        if (isset($_GET['etn_egr_import'], $_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'etn_egr_import_result')) {
            $import_msg = sanitize_text_field(wp_unslash($_GET['etn_egr_import']));
        }
        if ($import_msg === 'error_empty') {
            echo '<div class="notice notice-error"><p>' . esc_html__('No file was uploaded.', 'etchenet-reviews-for-google-business') . '</p></div>';
        } elseif ($import_msg === 'error_format') {
            echo '<div class="notice notice-error"><p>' . esc_html__('Invalid format. Use a .csv or .xlsx file.', 'etchenet-reviews-for-google-business') . '</p></div>';
        } elseif ($import_msg === 'error_no_data') {
            echo '<div class="notice notice-warning"><p>' . esc_html__('No valid reviews found (Author and Text are required per row).', 'etchenet-reviews-for-google-business') . '</p></div>';
        } elseif (is_numeric($import_msg) && (int) $import_msg > 0) {
            /* translators: %d: number of imported reviews */
            echo '<div class="notice notice-success"><p>' . sprintf(esc_html__('Successfully imported %d reviews.', 'etchenet-reviews-for-google-business'), (int) $import_msg) . '</p></div>';
        }
        ?>
        <div class="wrap etn-egr-admin-wrap" style="background:#f0f2f5; padding:20px; border-radius:10px;">
            <h1 style="margin-bottom:20px;">🚀 <?php echo esc_html__('Etchenet Reviews for Google Business', 'etchenet-reviews-for-google-business'); ?></h1>

            <div class="etn-egr-shortcode-box" style="margin-bottom:20px;padding:14px 18px;background:#fff;border:1px solid #c3c4c7;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.06);display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                <span style="font-weight:600;color:#1d2327;"><?php echo esc_html__('Carousel shortcode:', 'etchenet-reviews-for-google-business'); ?></span>
                <code id="etn-egr-shortcode-text" style="flex:1;min-width:200px;padding:8px 12px;background:#f6f7f7;border:1px solid #dcdcde;border-radius:4px;font-size:14px;">[etn_egr_reviews_carousel]</code>
                <button type="button" id="etn-egr-copy-shortcode" class="button button-secondary"><?php echo esc_html__('Copy shortcode', 'etchenet-reviews-for-google-business'); ?></button>
                <span id="etn-egr-copy-feedback" style="display:none;color:#00a32a;font-size:13px;"><?php echo esc_html__('Copied', 'etchenet-reviews-for-google-business'); ?></span>
            </div>

            <nav class="etn-egr-admin-tabs" role="tablist" style="margin-bottom:0;" aria-label="<?php echo esc_attr__('Settings sections', 'etchenet-reviews-for-google-business'); ?>">
                <button type="button" id="etn-egr-tab-btn-resenas" class="etn-egr-tab active" role="tab" data-tab="etn-egr-tab-resenas" aria-selected="true">✏️ <?php echo esc_html__('Reviews', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-layout" aria-selected="false">📐 <?php echo esc_html__('Layout (Slider)', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-filtros" aria-selected="false">🔍 <?php echo esc_html__('Filters & content', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-estetica" aria-selected="false">🎨 <?php echo esc_html__('Appearance', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-badge" aria-selected="false">📌 <?php echo esc_html__('Badge', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-panel" aria-selected="false">📋 <?php echo esc_html__('Side panel', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-conectividad" aria-selected="false">🔌 <?php echo esc_html__('Connectivity', 'etchenet-reviews-for-google-business'); ?></button>
                <button type="button" class="etn-egr-tab" role="tab" data-tab="etn-egr-tab-acerca" aria-selected="false">ℹ️ <?php echo esc_html__('About this plugin', 'etchenet-reviews-for-google-business'); ?></button>
            </nav>
            

            <!-- 1. Reseñas (contenido principal: añadir, importar, lista) -->
            <div id="etn-egr-tab-resenas" class="etn-egr-pane etn-egr-pane-active" role="tabpanel" aria-labelledby="etn-egr-tab-btn-resenas">
            <?php
                $manual_reviews = get_option(ETN_EGR_OPTION_MANUAL_REVIEWS, []);
                if (!is_array($manual_reviews)) {
                    $manual_reviews = [];
                }
                $api_reviews = isset($data['reviews']) && is_array($data['reviews']) ? $data['reviews'] : [];
                $list = [];
                foreach ($manual_reviews as $m) {
                    $key = isset($m['id']) ? $m['id'] : 'm_' . (isset($m['time']) ? $m['time'] : '');
                    $list[] = [
                        'etn_egr_key' => $key,
                        'author_name' => $m['author_name'] ?? '',
                        'text' => $m['text'] ?? '',
                        'rating' => (int) ($m['rating'] ?? 0),
                        'relative_time_description' => $m['relative_time_description'] ?? '—',
                        'time' => isset($m['time']) ? (int) $m['time'] : 0,
                        'origin' => 'manual',
                        'id' => $m['id'] ?? '',
                        'profile_photo_url' => function_exists('etn_egr_resolve_review_photo_url') ? etn_egr_resolve_review_photo_url($m) : ($m['profile_photo_url'] ?? ''),
                        'profile_photo_id' => isset($m['profile_photo_id']) ? (int) $m['profile_photo_id'] : '',
                        'visible' => isset($m['visible']) ? (bool) $m['visible'] : true,
                    ];
                }
                foreach ($api_reviews as $a) {
                    $list[] = [
                        'etn_egr_key' => 'g_' . (isset($a['time']) ? (int) $a['time'] : 0),
                        'author_name' => $a['author_name'] ?? '',
                        'text' => $a['text'] ?? '',
                        'rating' => (int) ($a['rating'] ?? 0),
                        'relative_time_description' => $a['relative_time_description'] ?? '—',
                        'time' => isset($a['time']) ? (int) $a['time'] : 0,
                        'origin' => 'google',
                        'id' => '',
                        'visible' => isset($a['visible']) ? (bool) $a['visible'] : true,
                    ];
                }
                $order = isset($s['reviews_order']) ? $s['reviews_order'] : 'date_desc';
                $order_manual = get_option(ETN_EGR_OPTION_REVIEWS_ORDER, []);
                if (!is_array($order_manual)) {
                    $order_manual = [];
                }
                if ($order === 'manual' && !empty($order_manual)) {
                    $by_key = [];
                    foreach ($list as $r) {
                        $by_key[$r['etn_egr_key']] = $r;
                    }
                    $sorted = [];
                    foreach ($order_manual as $key) {
                        if (isset($by_key[$key])) {
                            $sorted[] = $by_key[$key];
                            unset($by_key[$key]);
                        }
                    }
                    foreach ($by_key as $r) {
                        $sorted[] = $r;
                    }
                    $list = $sorted;
                } else {
                    usort($list, function ($a, $b) use ($order) {
                        $t1 = isset($a['time']) ? (int) $a['time'] : 0;
                        $t2 = isset($b['time']) ? (int) $b['time'] : 0;
                        $r1 = isset($a['rating']) ? (float) $a['rating'] : 0;
                        $r2 = isset($b['rating']) ? (float) $b['rating'] : 0;
                        switch ($order) {
                            case 'date_asc':
                                return $t1 - $t2;
                            case 'rating_desc':
                                if ($r2 !== $r1) {
                                    return $r2 > $r1 ? 1 : -1;
                                }
                                return $t2 - $t1;
                            case 'rating_asc':
                                if ($r1 !== $r2) {
                                    return $r1 > $r2 ? 1 : -1;
                                }
                                return $t2 - $t1;
                            default:
                                return $t2 - $t1;
                        }
                    });
                }
                $all_for_list = $list;
                $etn_egr_order_manual = ($order === 'manual');
                $etn_egr_manual_nonce = wp_create_nonce('etn_egr_manual_review');
                ?>
                <div style="margin-top:0;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.1);">
                    <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">✏️ <?php echo esc_html__('Manual reviews', 'etchenet-reviews-for-google-business'); ?></h3>
                    <p style="color:#555;margin-bottom:16px;">
                        <?php echo esc_html__('Add reviews with the same structure as Google reviews. They appear in the carousel and side panel alongside reviews from the API.', 'etchenet-reviews-for-google-business'); ?>
                    </p>

                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px;">
                        <div>
                            <p><label><?php echo esc_html__('Author name *', 'etchenet-reviews-for-google-business'); ?><br><input type="text" id="etn-egr-manual-author" class="large-text" placeholder="<?php echo esc_attr__('e.g. Jane Doe', 'etchenet-reviews-for-google-business'); ?>"></label></p>
                            <p><label><?php echo esc_html__('Review text *', 'etchenet-reviews-for-google-business'); ?><br><textarea id="etn-egr-manual-text" class="large-text" rows="4" placeholder="<?php echo esc_attr__('Write the review content…', 'etchenet-reviews-for-google-business'); ?>"></textarea></label></p>
                            <p><label><?php echo esc_html__('Stars (1–5)', 'etchenet-reviews-for-google-business'); ?><br><select id="etn-egr-manual-rating"><option value="5">5</option><option value="4">4</option><option value="3">3</option><option value="2">2</option><option value="1">1</option></select></label></p>
                        </div>
                        <div>
                            <p>
                                <label><?php echo esc_html__('Profile photo (optional)', 'etchenet-reviews-for-google-business'); ?></label><br>
                                <input type="hidden" id="etn-egr-manual-photo-id" value="">
                                <button type="button" id="etn-egr-select-photo-add" class="button"><?php echo esc_html__('Choose from media library', 'etchenet-reviews-for-google-business'); ?></button>
                                <button type="button" id="etn-egr-clear-photo-add" class="button" style="display:none;"><?php echo esc_html__('Remove image', 'etchenet-reviews-for-google-business'); ?></button>
                                <span id="etn-egr-manual-photo-preview-wrap" style="display:none;margin-top:8px;"><img id="etn-egr-manual-photo-preview" src="" alt="" style="max-width:60px;max-height:60px;border-radius:50%;object-fit:cover;"></span>
                            </p>
                            <p><label><?php echo esc_html__('Date label (optional)', 'etchenet-reviews-for-google-business'); ?><br><input type="text" id="etn-egr-manual-date" class="large-text" placeholder="<?php echo esc_attr__('e.g. 2 weeks ago', 'etchenet-reviews-for-google-business'); ?>"></label></p>
                            <p><button type="button" id="etn-egr-add-manual-btn" class="button button-primary"><?php echo esc_html__('Add review', 'etchenet-reviews-for-google-business'); ?></button></p>
                        </div>
                    </div>

                    <hr style="margin:20px 0;border:none;border-top:1px solid #ddd;">
                    <h4 style="margin:0 0 10px 0;">📥 <?php echo esc_html__('Import from Excel or CSV', 'etchenet-reviews-for-google-business'); ?></h4>
                    <p style="color:#555;margin-bottom:12px;">
                        <?php echo esc_html__('Upload a .xlsx or .csv file. The first row can be a header: Author, Text, Stars (1–5), Date, Photo URL. If there is no header, columns are read in that order (minimum: Author, Text).', 'etchenet-reviews-for-google-business'); ?>
                    </p>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                        <input type="hidden" name="action" value="etn_egr_import_reviews">
                        <?php wp_nonce_field('etn_egr_import_reviews'); ?>
                        <input type="file" name="etn_egr_import_file" accept=".csv,.xlsx" required>
                        <button type="submit" class="button button-secondary"><?php echo esc_html__('Import reviews', 'etchenet-reviews-for-google-business'); ?></button>
                    </form>

                    <h4 style="margin:24px 0 10px 0;"><?php echo esc_html__('Full list of reviews', 'etchenet-reviews-for-google-business'); ?> (<?php echo count($all_for_list); ?>: <?php echo count($manual_reviews); ?> <?php echo esc_html__('manual', 'etchenet-reviews-for-google-business'); ?>, <?php echo count($api_reviews); ?> <?php echo esc_html__('from Google', 'etchenet-reviews-for-google-business'); ?>)</h4>
                    <p style="color:#50575e;margin-bottom:10px;"><?php echo esc_html__('Drag rows by the ⋮⋮ column to reorder, then click “Save current order.” That order is used in the carousel and side panel.', 'etchenet-reviews-for-google-business'); ?></p>
                    <?php if (!empty($all_for_list)) : ?>
                    <p style="margin-bottom:10px;">
                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=etn_egr_export_reviews'), 'etn_egr_export_reviews')); ?>" class="button button-secondary"><?php echo esc_html__('Export all reviews (CSV)', 'etchenet-reviews-for-google-business'); ?></a>
                    </p>
                    <?php endif; ?>
                    
                    <?php if (!empty($all_for_list)) : ?>
                        <p style="margin-bottom:10px;">
                            <button type="button" id="etn-egr-save-order-btn" class="button button-secondary"><?php echo esc_html__('Save current order', 'etchenet-reviews-for-google-business'); ?></button>
                            <button type="button" id="etn-egr-bulk-delete-btn" class="button button-secondary" style="margin-left:8px;"><?php echo esc_html__('Delete selected', 'etchenet-reviews-for-google-business'); ?></button>
                            <span id="etn-egr-save-order-msg" style="margin-left:10px;"></span>
                        </p>
                    <?php endif; ?>
                    <table class="wp-list-table widefat fixed striped" id="etn-egr-reviews-table">
                        <thead>
                            <tr>
                                <th style="width:36px;" title="<?php echo esc_attr__('Drag to reorder', 'etchenet-reviews-for-google-business'); ?>"></th>
                                <th style="width:32px;"><input type="checkbox" id="etn-egr-select-all-manual" title="<?php echo esc_attr__('Select all manual reviews', 'etchenet-reviews-for-google-business'); ?>"></th>
                                <th style="width:100px;"><?php echo esc_html__('Source', 'etchenet-reviews-for-google-business'); ?></th>
                                <th style="width:70px;"><?php echo esc_html__('Visible', 'etchenet-reviews-for-google-business'); ?></th>
                                <th style="width:140px;"><?php echo esc_html__('Autor', 'etchenet-reviews-for-google-business'); ?></th>
                                <th><?php echo esc_html__('Excerpt', 'etchenet-reviews-for-google-business'); ?></th>
                                <th style="width:80px;"><?php echo esc_html__('Stars', 'etchenet-reviews-for-google-business'); ?></th>
                                <th style="width:120px;"><?php echo esc_html__('Date / added', 'etchenet-reviews-for-google-business'); ?></th>
                                <th style="width:90px;"><?php echo esc_html__('Actions', 'etchenet-reviews-for-google-business'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="etn-egr-reviews-tbody">
                            <?php if (empty($all_for_list)) : ?>
                                <tr><td colspan="9"><?php echo esc_html__('No reviews yet. Sync with Google or add a manual review above.', 'etchenet-reviews-for-google-business'); ?></td></tr>
                            <?php else : ?>
                                <?php foreach ($all_for_list as $row) : ?>
                                    <?php
                                    $row_visible = isset($row['visible']) ? (bool) $row['visible'] : true;
                                    ?>
                                    <tr data-id="<?php echo esc_attr($row['id']); ?>" data-etn-egr-key="<?php echo esc_attr($row['etn_egr_key']); ?>"<?php echo ( $row['origin'] === 'manual' && $row['id'] !== '' ) ? ' data-review="' . esc_attr( wp_json_encode( [
                                        'id' => $row['id'],
                                        'author_name' => $row['author_name'],
                                        'text' => $row['text'],
                                        'rating' => (int) $row['rating'],
                                        'relative_time_description' => $row['relative_time_description'],
                                        'profile_photo_url' => isset( $row['profile_photo_url'] ) ? $row['profile_photo_url'] : '',
                                        'profile_photo_id' => isset( $row['profile_photo_id'] ) ? (int) $row['profile_photo_id'] : '',
                                        'visible' => $row_visible,
                                    ] ) ) . '"' : ''; ?>>
                                        <td class="etn-egr-drag-handle" title="<?php echo esc_attr__('Drag to reorder', 'etchenet-reviews-for-google-business'); ?>">⋮⋮</td>
                                        <td><?php if ($row['origin'] === 'manual' && $row['id'] !== '') : ?><input type="checkbox" class="etn-egr-row-checkbox" value="<?php echo esc_attr($row['id']); ?>"><?php else : ?>—<?php endif; ?></td>
                                        <td><?php echo $row['origin'] === 'manual' ? esc_html__('Manual', 'etchenet-reviews-for-google-business') : esc_html__('Google', 'etchenet-reviews-for-google-business'); ?></td>
                                        <td><label title="<?php echo esc_attr__('Visible in carousel and side panel', 'etchenet-reviews-for-google-business'); ?>"><input type="checkbox" class="etn-egr-visible-checkbox" <?php echo $row_visible ? ' checked' : ''; ?> data-etn-egr-key="<?php echo esc_attr($row['etn_egr_key']); ?>"> <?php echo esc_html__('Yes', 'etchenet-reviews-for-google-business'); ?></label></td>
                                        <td><?php echo esc_html($row['author_name']); ?></td>
                                        <td><?php echo esc_html(wp_trim_words($row['text'], 12)); ?></td>
                                        <td><?php echo (int) $row['rating']; ?> ★</td>
                                        <td><?php echo esc_html($row['relative_time_description']); ?></td>
                                        <td>
                                            <?php if ($row['origin'] === 'manual' && $row['id'] !== '') : ?>
                                                <button type="button" class="button button-small etn-egr-edit-manual"><?php echo esc_html__('Edit', 'etchenet-reviews-for-google-business'); ?></button>
                                                <button type="button" class="button button-small etn-egr-delete-manual" data-id="<?php echo esc_attr($row['id']); ?>"><?php echo esc_html__('Delete', 'etchenet-reviews-for-google-business'); ?></button>
                                            <?php else : ?>
                                                —
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <!-- / Pestaña Reseñas -->

            <form method="post" action="options.php" id="etn-egr-settings-form">
                <?php settings_fields('etn_egr_settings'); ?>

                <!-- Pestaña: Layout (Slider) -->
                <div id="etn-egr-tab-layout" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box etn-egr-layout-full">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">📐 <?php echo esc_html__('Layout (Slider)', 'etchenet-reviews-for-google-business'); ?></h3>
                        <div class="etn-egr-preview-layout-wrap">
                            <div class="etn-egr-admin-preview" id="etn-egr-preview-layout" style="padding:16px;background:#f6f7f7;border-radius:8px;border:1px solid #c3c4c7;">
                                <p style="margin:0 0 10px 0;font-size:12px;color:#50575e;"><?php echo esc_html__('Preview (carousel cards)', 'etchenet-reviews-for-google-business'); ?></p>
                                <div class="etn-egr-preview-cards-row" style="display:flex;gap:<?php echo (int) ($s['card_gap'] ?? 12); ?>px;flex-wrap:wrap;">
                                    <?php
                                    $cols = (int) ($s['columns'] ?? 3);
                                    $card_pad = (int) ($s['card_padding'] ?? 16);
                                    $radius = (int) ($s['border_radius'] ?? 8);
                                    $card_bg = esc_attr($s['bg_card'] ?? '#ffffff');
                                    for ($i = 0; $i < 6; $i++) :
                                    ?>
                                    <div class="etn-egr-preview-card" style="flex:1;min-width:80px;max-width:120px;background:<?php echo esc_attr( $s['bg_card'] ?? '#ffffff' ); ?>;padding:<?php echo absint( $card_pad ); ?>px;border-radius:<?php echo absint( $radius ); ?>px;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
                                        <div style="color:<?php echo esc_attr($s['c_name'] ?? '#333'); ?>;font-weight:bold;font-size:11px;"><?php echo esc_html__('Author', 'etchenet-reviews-for-google-business' ); ?></div>
                                        <div style="color:<?php echo esc_attr($s['c_star'] ?? '#ffc107'); ?>;font-size:10px;">★★★★★</div>
                                        <div style="color:<?php echo esc_attr($s['c_text'] ?? '#555'); ?>;font-size:10px;margin-top:4px;"><?php echo esc_html__('Review text…', 'etchenet-reviews-for-google-business' ); ?></div>
                                    </div>
                                    <?php endfor; ?>
                                </div>
                            </div>
                        </div>
                        <div class="etn-egr-params-cols">
                            <div>
                                <p>
                                    <?php echo esc_html__('Columns on desktop (≥1024px):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[columns]"
                                           value="<?php echo (int) $s['columns']; ?>" min="1" max="6">
                                </p>
                                <p>
                                    <label>
                                        <input type="checkbox" name="etn_egr_style_options[equal_height]" value="1"
                                            <?php checked(1, (int) $s['equal_height']); ?>>
                                        <?php echo esc_html__('Equal height (all cards aligned)', 'etchenet-reviews-for-google-business'); ?>
                                    </label>
                                </p>
                                <p>
                                    <label>
                                        <input type="checkbox" name="etn_egr_style_options[autoplay]" value="1"
                                            <?php checked(1, (int) $s['autoplay']); ?>>
                                        <?php echo esc_html__('Enable autoplay', 'etchenet-reviews-for-google-business'); ?>
                                    </label>
                                </p>
                                <p>
                                    <?php echo esc_html__('Speed (ms):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[speed]"
                                           value="<?php echo (int) $s['speed']; ?>" min="500" step="100">
                                </p>
                                <p>
                                    <label>
                                        <input type="checkbox" name="etn_egr_style_options[arrows]" value="1"
                                            <?php checked(1, (int) $s['arrows']); ?>>
                                        <?php echo esc_html__('Show navigation arrows', 'etchenet-reviews-for-google-business'); ?>
                                    </label>
                                </p>
                                <p>
                                    <label>
                                        <input type="checkbox" name="etn_egr_style_options[arrows_circle]" value="1"
                                            <?php checked(1, (int) ($s['arrows_circle'] ?? 1)); ?>>
                                        <?php echo esc_html__('Circular arrow buttons', 'etchenet-reviews-for-google-business'); ?>
                                    </label>
                                </p>
                                <p>
                                    <?php echo esc_html__('Arrow circle background color:', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="text" name="etn_egr_style_options[arrow_bg_color]"
                                           value="<?php echo esc_attr($s['arrow_bg_color'] ?? '#ffffff'); ?>"
                                           class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                                </p>
                                <p>
                                    <?php echo esc_html__('Arrow icon color:', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="text" name="etn_egr_style_options[arrow_icon_color]"
                                           value="<?php echo esc_attr($s['arrow_icon_color'] ?? '#555555'); ?>"
                                           class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                                </p>
                                <p>
                                    <?php echo esc_html__('Arrow size (px):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[arrow_size]"
                                           value="<?php echo (int) ($s['arrow_size'] ?? 40); ?>" min="24" max="80" step="2">
                                </p>
                                <p>
                                    <?php echo esc_html__('Horizontal arrow position:', 'etchenet-reviews-for-google-business'); ?><br>
                                    <select name="etn_egr_style_options[arrow_pos_h]">
                                        <option value="limit" <?php selected('limit', $s['arrow_pos_h'] ?? 'limit'); ?>><?php echo esc_html__('At the edge (half outside, half inside)', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="exterior" <?php selected('exterior', $s['arrow_pos_h'] ?? ''); ?>><?php echo esc_html__('Outside', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="interior" <?php selected('interior', $s['arrow_pos_h'] ?? ''); ?>><?php echo esc_html__('Inside', 'etchenet-reviews-for-google-business'); ?></option>
                                    </select>
                                </p>
                                <p>
                                    <?php echo esc_html__('Vertical arrow position:', 'etchenet-reviews-for-google-business'); ?><br>
                                    <select name="etn_egr_style_options[arrow_pos_v]">
                                        <option value="top" <?php selected('top', $s['arrow_pos_v'] ?? ''); ?>><?php echo esc_html__('Top', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="middle" <?php selected('middle', $s['arrow_pos_v'] ?? 'middle'); ?>><?php echo esc_html__('Middle', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="bottom" <?php selected('bottom', $s['arrow_pos_v'] ?? ''); ?>><?php echo esc_html__('Bottom', 'etchenet-reviews-for-google-business'); ?></option>
                                    </select>
                                </p>
                                <p>
                                    <label>
                                        <input type="checkbox" name="etn_egr_style_options[dots]" value="1"
                                            <?php checked(1, (int) $s['dots']); ?>>
                                        <?php echo esc_html__('Show pagination dots', 'etchenet-reviews-for-google-business'); ?>
                                    </label>
                                </p>
                            </div>
                            <div>
                                <p>
                                    <?php echo esc_html__('Card aspect ratio (carousel):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <select name="etn_egr_style_options[card_aspect_ratio]">
                                        <option value="16_9" <?php selected('16_9', $s['card_aspect_ratio'] ?? '16_9'); ?>><?php echo esc_html__('16:9 (landscape)', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="4_3" <?php selected('4_3', $s['card_aspect_ratio'] ?? ''); ?>><?php echo esc_html__('4:3', 'etchenet-reviews-for-google-business'); ?></option>
                                        <option value="auto" <?php selected('auto', $s['card_aspect_ratio'] ?? ''); ?>><?php echo esc_html__('Automatic (by content)', 'etchenet-reviews-for-google-business'); ?></option>
                                    </select>
                                </p>
                                <p>
                                    <?php echo esc_html__('Card inner padding (px):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[card_padding]"
                                           value="<?php echo (int) ($s['card_padding'] ?? 16); ?>" min="8" max="48" step="2">
                                </p>
                                <p>
                                    <?php echo esc_html__('Gap between cards (px):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[card_gap]"
                                           value="<?php echo (int) ($s['card_gap'] ?? 12); ?>" min="0" max="40" step="2">
                                </p>
                                <p>
                                    <?php echo esc_html__('Space between review text and “Read more” (carousel, px):', 'etchenet-reviews-for-google-business'); ?><br>
                                    <input type="number" name="etn_egr_style_options[card_read_more_gap]"
                                           value="<?php echo (int) ($s['card_read_more_gap'] ?? 4); ?>" min="0" max="24" step="1">
                                    <span style="color:#646970;font-size:12px;"> <?php echo esc_html__('Inner space between the text and the “Read more” link inside the card.', 'etchenet-reviews-for-google-business'); ?></span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Pestaña: Filtros y Contenido -->
                <div id="etn-egr-tab-filtros" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">🔍 <?php echo esc_html__('Filters & content', 'etchenet-reviews-for-google-business'); ?></h3>
                        <p style="font-size:12px;color:#50575e;margin-bottom:16px;"><?php echo esc_html__('Options on this tab affect displayed content (minimum stars, excerpt, etc.). Appearance is set under Appearance and Layout.', 'etchenet-reviews-for-google-business'); ?></p>
                        <p>
                            <?php echo esc_html__('Minimum stars to show:', 'etchenet-reviews-for-google-business'); ?><br>
                            <select name="etn_egr_style_options[min_stars]">
                                <?php for ($i = 1; $i <= 5; $i++) : ?>
                                    <option value="<?php echo (int) $i; ?>" <?php selected($i, (int) $s['min_stars']); ?>>
                                        <?php echo (int) $i; ?>+
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[exclude_empty]" value="1"
                                    <?php checked(1, (int) $s['exclude_empty']); ?>>
                                <?php echo esc_html__('Exclude reviews with no text', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[show_avatar]" value="1"
                                    <?php checked(1, (int) $s['show_avatar']); ?>>
                                <?php echo esc_html__('Show author profile photo (small circle next to the name)', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                        <p>
                            <?php echo esc_html__('Excerpt length (characters on the card):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[excerpt_length]"
                                   value="<?php echo (int) $s['excerpt_length']; ?>" min="50" max="500" step="10">
                            <span style="color:#646970;font-size:12px;"> <?php echo esc_html__('(50–500). The same length applies to every review (Google and manual) in the carousel and side panel.', 'etchenet-reviews-for-google-business'); ?></span>
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[show_read_more]" value="1"
                                    <?php checked(1, (int) $s['show_read_more']); ?>>
                                <?php echo esc_html__('Show “Read more” with the full review text', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                        <p>
                            <?php echo esc_html__('Review order (carousel, badge, and side panel):', 'etchenet-reviews-for-google-business'); ?><br>
                            <select name="etn_egr_style_options[reviews_order]">
                                <option value="date_desc" <?php selected('date_desc', $s['reviews_order'] ?? 'date_desc'); ?>><?php echo esc_html__('Newest first', 'etchenet-reviews-for-google-business'); ?></option>
                                <option value="date_asc" <?php selected('date_asc', $s['reviews_order'] ?? ''); ?>><?php echo esc_html__('Oldest first', 'etchenet-reviews-for-google-business'); ?></option>
                                <option value="rating_desc" <?php selected('rating_desc', $s['reviews_order'] ?? ''); ?>><?php echo esc_html__('Highest rated first', 'etchenet-reviews-for-google-business'); ?></option>
                                <option value="rating_asc" <?php selected('rating_asc', $s['reviews_order'] ?? ''); ?>><?php echo esc_html__('Lowest rated first', 'etchenet-reviews-for-google-business'); ?></option>
                                <option value="manual" <?php selected('manual', $s['reviews_order'] ?? ''); ?>><?php echo esc_html__('Manual order (drag in the list)', 'etchenet-reviews-for-google-business'); ?></option>
                            </select>
                        </p>
                    </div>
                </div>

                <!-- Pestaña: Estética -->
                <div id="etn-egr-tab-estetica" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">🎨 <?php echo esc_html__('Appearance', 'etchenet-reviews-for-google-business'); ?></h3>
                        <div class="etn-egr-admin-preview" id="etn-egr-preview-estetica" style="margin-bottom:20px;padding:16px;background:#f6f7f7;border-radius:8px;border:1px solid #c3c4c7;">
                            <p style="margin:0 0 10px 0;font-size:12px;color:#50575e;"><?php echo esc_html__('Preview (review card)', 'etchenet-reviews-for-google-business'); ?></p>
                            <div class="etn-egr-preview-card-single" style="max-width:280px;background:<?php echo esc_attr($s['bg_card']); ?>;padding:16px;border-radius:<?php echo (int) $s['border_radius']; ?>px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
                                <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                                    <div style="width:32px;height:32px;border-radius:50%;background:#ddd;"></div>
                                    <div style="color:<?php echo esc_attr($s['c_name']); ?>;font-weight:bold;font-size:13px;"><?php echo esc_html__('Author name', 'etchenet-reviews-for-google-business'); ?></div>
                                </div>
                                <div style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:14px;">★★★★★</div>
                                <div style="color:<?php echo esc_attr($s['c_text']); ?>;font-size:12px;margin-top:8px;line-height:1.4;"><?php echo esc_html__('Sample review text as it will appear on the card.', 'etchenet-reviews-for-google-business'); ?></div>
                            </div>
                        </div>
                        <p>
                            <?php echo esc_html__('Card background:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[bg_card]"
                                   value="<?php echo esc_attr($s['bg_card']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Author name color:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[c_name]"
                                   value="<?php echo esc_attr($s['c_name']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Review text color:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[c_text]"
                                   value="<?php echo esc_attr($s['c_text']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Star color:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[c_star]"
                                   value="<?php echo esc_attr($s['c_star']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Border radius (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[border_radius]"
                                   value="<?php echo (int) $s['border_radius']; ?>" min="0" max="50">
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[rich_snippets]" value="1"
                                    <?php checked(1, (int) $s['rich_snippets']); ?>>
                                <?php echo esc_html__('Enable Rich Snippets (JSON-LD) for SEO', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                    </div>
                </div>

                <!-- Pestaña: Badge flotante -->
                <div id="etn-egr-tab-badge" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">📌 <?php echo esc_html__('Floating badge', 'etchenet-reviews-for-google-business'); ?></h3>
                        <div class="etn-egr-admin-preview" id="etn-egr-preview-badge" style="margin-bottom:20px;padding:16px;background:#f6f7f7;border-radius:8px;border:1px solid #c3c4c7;">
                            <p style="margin:0 0 10px 0;font-size:12px;color:#50575e;"><?php echo esc_html__('Preview (badge)', 'etchenet-reviews-for-google-business'); ?></p>
                                    <div class="etn-egr-preview-badge-inner" style="display:inline-flex;align-items:center;gap:8px;background:#fff;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);">
                                <span style="width:24px;height:24px;background:#ddd;border-radius:4px;"></span>
                                <div style="line-height:1.2;">
                                    <div class="etn-egr-preview-badge-stars" style="color:<?php echo esc_attr($s['c_star']); ?>;font-size:11px;">★★★★★</div>
                                    <div style="font-size:11px;color:#333;"><strong>4.8</strong> <span style="color:#999;">/ 5</span><br><span style="font-size:10px;color:#666;"><?php echo esc_html__('12 reviews', 'etchenet-reviews-for-google-business' ); ?></span></div>
                                </div>
                                <span class="etn-egr-preview-badge-plus" style="flex-shrink:0;width:22px;height:22px;border-radius:50%;background:<?php echo esc_attr($s['c_star']); ?>;color:#fff;font-size:14px;line-height:22px;text-align:center;<?php echo empty($s['write_review_url']) ? 'display:none;' : ''; ?>">+</span>
                            </div>
                        </div>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[show_badge]" value="1"
                                    <?php checked(1, (int) $s['show_badge']); ?>>
                                <?php echo esc_html__('Show floating badge', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                        <p>
                            <?php echo esc_html__('Position:', 'etchenet-reviews-for-google-business'); ?><br>
                            <select name="etn_egr_style_options[badge_pos]">
                                <option value="right" <?php selected('right', $s['badge_pos']); ?>><?php echo esc_html__('Right', 'etchenet-reviews-for-google-business'); ?></option>
                                <option value="left" <?php selected('left', $s['badge_pos']); ?>><?php echo esc_html__('Left', 'etchenet-reviews-for-google-business'); ?></option>
                            </select>
                        </p>
                        <p>
                            <?php echo esc_html__('Side margin (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[badge_m_side]"
                                   value="<?php echo (int) $s['badge_m_side']; ?>" min="0">
                        </p>
                        <p>
                            <?php echo esc_html__('Bottom margin (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[badge_m_bottom]"
                                   value="<?php echo (int) $s['badge_m_bottom']; ?>" min="0">
                        </p>
                        <p>
                            <?php echo esc_html__('Inner padding (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[badge_padding]"
                                   value="<?php echo (int) $s['badge_padding']; ?>" min="0">
                        </p>
                        <p>
                            <?php echo esc_html__('URL for “Write a review” (link to leave a Google review):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="url" name="etn_egr_style_options[write_review_url]"
                                   value="<?php echo esc_attr($s['write_review_url'] ?? ''); ?>"
                                   class="large-text" placeholder="https://search.google.com/local/writereview?placeid=...">
                            <span style="color:#646970;font-size:12px;display:block;margin-top:4px;"><?php echo esc_html__('Optional. If empty, the link is not shown in the panel.', 'etchenet-reviews-for-google-business'); ?></span>
                        </p>
                    </div>
                </div>

                <!-- Pestaña: Panel lateral -->
                <div id="etn-egr-tab-panel" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">📋 <?php echo esc_html__('Side panel (when clicking the badge)', 'etchenet-reviews-for-google-business'); ?></h3>
                        <div class="etn-egr-admin-preview" id="etn-egr-preview-panel" style="margin-bottom:20px;padding:16px;background:#f6f7f7;border-radius:8px;border:1px solid #c3c4c7;">
                            <p style="margin:0 0 10px 0;font-size:12px;color:#50575e;"><?php echo esc_html__('Preview (panel)', 'etchenet-reviews-for-google-business'); ?></p>
                            <div class="etn-egr-preview-panel-inner" style="max-width:220px;background:<?php echo esc_attr($s['sidebar_bg']); ?>;padding:<?php echo (int) $s['sidebar_padding']; ?>px;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']); ?>;">
                                <div style="color:rgba(255,255,255,0.9);font-size:11px;font-weight:bold;margin-bottom:6px;"><?php echo esc_html__('Google reviews', 'etchenet-reviews-for-google-business'); ?></div>
                                <div style="color:rgba(255,255,255,0.8);font-size:10px;"><?php echo esc_html__('★ 4.8 / 5 (12)', 'etchenet-reviews-for-google-business' ); ?></div>
                                <div class="etn-egr-preview-panel-card" style="margin-top:10px;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;">
                                    <div style="font-weight:bold;font-size:10px;color:rgba(255,255,255,0.95);"><?php echo esc_html__('Author', 'etchenet-reviews-for-google-business' ); ?></div>
                                    <div style="font-size:9px;color:rgba(255,255,255,0.8);margin-top:4px;"><?php echo esc_html__('Review text…', 'etchenet-reviews-for-google-business' ); ?></div>
                                </div>
                            </div>
                        </div>
                        <p style="font-size:12px;color:#555;margin-bottom:15px;">
                            <?php echo esc_html__('The side panel opens when the visitor clicks the floating badge.', 'etchenet-reviews-for-google-business'); ?>
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_style_options[sidebar_header_sticky]" value="1"
                                    <?php checked(1, (int) ($s['sidebar_header_sticky'] ?? 1)); ?>>
                                <?php echo esc_html__('Sticky panel header', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                            <span style="color:#646970;font-size:12px;display:block;margin-top:4px;"> <?php echo esc_html__('The title, rating, and close button stay visible while scrolling the panel.', 'etchenet-reviews-for-google-business'); ?></span>
                        </p>
                        <p>
                            <?php echo esc_html__('Panel width (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_width]"
                                   value="<?php echo (int) $s['sidebar_width']; ?>" min="300" max="800" step="10">
                        </p>
                        <p>
                            <?php echo esc_html__('Panel background color:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[sidebar_bg]"
                                   value="<?php echo esc_attr($s['sidebar_bg']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Panel padding (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_padding]"
                                   value="<?php echo (int) $s['sidebar_padding']; ?>" min="10" max="50">
                        </p>
                        <p>
                            <?php echo esc_html__('Panel border radius (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_border_radius]"
                                   value="<?php echo (int) $s['sidebar_border_radius']; ?>" min="0" max="30">
                        </p>
                        <p>
                            <?php echo esc_html__('Panel shadow (CSS box-shadow):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[sidebar_shadow]"
                                   value="<?php echo esc_attr($s['sidebar_shadow']); ?>" class="regular-text"
                                   placeholder="0 4px 20px rgba(0,0,0,0.3)">
                        </p>
                        <p>
                            <?php echo esc_html__('Maximum panel height:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[sidebar_max_height]"
                                   value="<?php echo esc_attr($s['sidebar_max_height']); ?>" class="regular-text"
                                   placeholder="80vh">
                        </p>
                        <p>
                            <?php echo esc_html__('Maximum reviews in the panel (0 = all):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_max_reviews]"
                                   value="<?php echo (int) ($s['sidebar_max_reviews'] ?? 0); ?>" min="0" max="200" step="1">
                        </p>
                        <hr style="margin:15px 0;border:none;border-top:1px solid #ddd;">
                        <h4 style="margin-top:0;font-size:14px;"><?php echo esc_html__('Review card styles', 'etchenet-reviews-for-google-business'); ?></h4>
                        <p>
                            <?php echo esc_html__('Card background:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_style_options[sidebar_card_bg]"
                                   value="<?php echo esc_attr($s['sidebar_card_bg']); ?>" class="etn-egr-color-input wp-color-picker" data-alpha-enabled="true">
                        </p>
                        <p>
                            <?php echo esc_html__('Card padding (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_card_padding]"
                                   value="<?php echo (int) $s['sidebar_card_padding']; ?>" min="5" max="30">
                        </p>
                        <p>
                            <?php echo esc_html__('Gap between cards (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_card_margin]"
                                   value="<?php echo (int) $s['sidebar_card_margin']; ?>" min="5" max="30">
                        </p>
                        <p>
                            <?php echo esc_html__('Card border radius (px):', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="number" name="etn_egr_style_options[sidebar_card_border_radius]"
                                   value="<?php echo (int) $s['sidebar_card_border_radius']; ?>" min="0" max="20">
                        </p>
                    </div>
                </div>

                <!-- Pestaña: Conectividad (al final: una vez configurada, se usa poco) -->
                <div id="etn-egr-tab-conectividad" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">🔌 <?php echo esc_html__('Connectivity', 'etchenet-reviews-for-google-business'); ?></h3>
                        <p><?php echo esc_html__('Google API Key:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="password" name="etn_egr_api_key"
                                   value="<?php echo esc_attr(get_option('etn_egr_api_key', get_option('grp_api_key', ''))); ?>"
                                   class="large-text" autocomplete="off">
                        </p>
                        <p><?php echo esc_html__('Place ID:', 'etchenet-reviews-for-google-business'); ?><br>
                            <input type="text" name="etn_egr_place_id"
                                   value="<?php echo esc_attr(get_option('etn_egr_place_id', get_option('grp_place_id', ''))); ?>"
                                   class="large-text" autocomplete="off">
                        </p>
                        <div class="notice notice-info" style="margin:16px 0;padding:12px 16px;max-width:640px;">
                            <p style="margin:0 0 8px 0;"><strong><?php echo esc_html__('How syncing with Google works', 'etchenet-reviews-for-google-business'); ?></strong></p>
                            <p style="margin:0;font-size:13px;line-height:1.5;">
                                <?php echo esc_html__('This plugin uses the Google Places API (Place Details) to fetch reviews. Google returns a limited number of reviews per request (often five) and does not offer pagination. To collect more over time: (1) Sync periodically — each run only adds new reviews and merges them with what is already stored, without removing older ones. (2) Add manual reviews or import CSV/Excel; those are unlimited and appear alongside Google reviews. See the readme and plugin settings for more detail.', 'etchenet-reviews-for-google-business'); ?>
                            </p>
                        </div>
                        <p style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
                            <button type="button" id="etn-egr-sync-btn" class="button button-primary">
                                <?php echo esc_html__('Sync now', 'etchenet-reviews-for-google-business'); ?>
                            </button>
                            <button type="button" id="etn-egr-reset-google-btn" class="button" style="color:#d63638;border-color:#d63638;">
                                <?php echo esc_html__('Delete Google reviews and re-sync', 'etchenet-reviews-for-google-business'); ?>
                            </button>
                        </p>
                        <p><b><?php echo esc_html__('Status:', 'etchenet-reviews-for-google-business'); ?></b>
                            <?php
                            $api_count = $data && !empty($data['reviews']) ? count($data['reviews']) : 0;
                            $manual_count = count(get_option(ETN_EGR_OPTION_MANUAL_REVIEWS, []));
                            $total_count = $api_count + $manual_count;
                            if ($total_count > 0) {
                                /* translators: %d: total number of reviews */
                                echo '✅ ' . sprintf(esc_html__('%d reviews in total', 'etchenet-reviews-for-google-business'), (int) $total_count);
                                if ($manual_count > 0) {
                                    /* translators: 1: number of manual reviews, 2: number of Google reviews */
                                    echo ' (' . sprintf(esc_html__('%1$d manual review(s), %2$d from Google', 'etchenet-reviews-for-google-business'), (int) $manual_count, (int) $api_count) . ').';
                                } else {
                                    echo ' (' . esc_html__('from Google', 'etchenet-reviews-for-google-business') . ').';
                                }
                            } else {
                                echo '❌ ' . esc_html__('No data yet. Sync from Google or add manual reviews.', 'etchenet-reviews-for-google-business');
                            }
                            ?>
                        </p>
                        <p>
                            <label>
                                <input type="checkbox" name="etn_egr_enable_cron" value="1"
                                    <?php checked(1, (int) get_option('etn_egr_enable_cron', get_option('grp_enable_cron', 1))); ?>>
                                <?php echo esc_html__('Enable daily automatic sync (WP-Cron)', 'etchenet-reviews-for-google-business'); ?>
                            </label>
                        </p>
                        <p style="font-size:12px;color:#555;margin-top:10px;">
                            <?php echo esc_html__('If you see REQUEST_DENIED when syncing, check your API key’s referrer restrictions in Google Cloud.', 'etchenet-reviews-for-google-business'); ?>
                        </p>
                    </div>
                </div>

                <!-- Pestaña: Sobre el plugin -->
                <div id="etn-egr-tab-acerca" class="etn-egr-pane" role="tabpanel" hidden>
                    <div class="etn-egr-pane-box">
                        <h3 style="border-bottom:2px solid #2271b1;padding-bottom:10px;">ℹ️ <?php echo esc_html__('About this plugin', 'etchenet-reviews-for-google-business'); ?></h3>
                        <p style="margin:0 0 1em 0;font-size:14px;line-height:1.6;">
                            <?php echo esc_html__('Plugin by Etchenet. Displays Google reviews in a carousel, floating badge, and side panel. Add manual reviews, import CSV/Excel, and sync with the Google Places API.', 'etchenet-reviews-for-google-business'); ?>
                        </p>
                        <p style="margin:0;font-size:13px;">
                            <?php echo esc_html__('Website:', 'etchenet-reviews-for-google-business'); ?> <a href="<?php echo esc_url( 'http://etchenet.com' ); ?>" target="_blank" rel="noopener noreferrer">http://etchenet.com</a><br>
                            <?php echo esc_html__('Support / donate:', 'etchenet-reviews-for-google-business'); ?> <a href="<?php echo esc_url( 'https://www.paypal.com/paypalme/etchenet/' ); ?>" target="_blank" rel="noopener noreferrer">PayPal.Me</a>
                        </p>
                    </div>
                </div>

                <div style="margin-top:20px;">
                    <?php submit_button(__('Save all changes', 'etchenet-reviews-for-google-business')); ?>
                </div>
            </form>

                <!-- Modal editar reseña manual -->
                <div id="etn-egr-edit-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100000;align-items:center;justify-content:center;">
                    <div style="background:#fff;padding:24px;border-radius:8px;max-width:560px;width:90%;max-height:90vh;overflow:auto;box-shadow:0 4px 20px rgba(0,0,0,0.2);">
                        <h3 style="margin-top:0;"><?php echo esc_html__('Edit manual review', 'etchenet-reviews-for-google-business'); ?></h3>
                        <form id="etn-egr-edit-form">
                            <input type="hidden" name="id" id="etn-egr-edit-id" value="">
                            <p><label><?php echo esc_html__('Author name *', 'etchenet-reviews-for-google-business'); ?><br><input type="text" name="author_name" id="etn-egr-edit-author" class="large-text" required></label></p>
                            <p><label><?php echo esc_html__('Review text *', 'etchenet-reviews-for-google-business'); ?><br><textarea name="text" id="etn-egr-edit-text" class="large-text" rows="4" required></textarea></label></p>
                            <p><label><?php echo esc_html__('Stars (1–5)', 'etchenet-reviews-for-google-business'); ?><br><select name="rating" id="etn-egr-edit-rating"><option value="5">5</option><option value="4">4</option><option value="3">3</option><option value="2">2</option><option value="1">1</option></select></label></p>
                            <p>
                                <label><?php echo esc_html__('Profile photo (optional)', 'etchenet-reviews-for-google-business'); ?></label><br>
                                <input type="hidden" name="profile_photo_id" id="etn-egr-edit-photo-id" value="">
                                <input type="hidden" id="etn-egr-edit-photo-url" value="">
                                <button type="button" id="etn-egr-select-photo-edit" class="button"><?php echo esc_html__('Choose from media library', 'etchenet-reviews-for-google-business'); ?></button>
                                <button type="button" id="etn-egr-clear-photo-edit" class="button" style="display:none;"><?php echo esc_html__('Remove image', 'etchenet-reviews-for-google-business'); ?></button>
                                <span id="etn-egr-edit-photo-preview-wrap" style="display:none;margin-top:8px;"><img id="etn-egr-edit-photo-preview" src="" alt="" style="max-width:60px;max-height:60px;border-radius:50%;object-fit:cover;"></span>
                            </p>
                            <p><label><?php echo esc_html__('Date label (optional)', 'etchenet-reviews-for-google-business'); ?><br><input type="text" name="relative_time_description" id="etn-egr-edit-date" class="large-text" placeholder="<?php echo esc_attr__('e.g. 2 weeks ago', 'etchenet-reviews-for-google-business'); ?>"></label></p>
                            <p><label><input type="checkbox" name="visible" id="etn-egr-edit-visible" value="1" checked> <?php echo esc_html__('Visible in carousel and side panel', 'etchenet-reviews-for-google-business'); ?></label></p>
                            <p style="margin-bottom:0;">
                                <button type="submit" class="button button-primary" id="etn-egr-edit-submit"><?php echo esc_html__('Save changes', 'etchenet-reviews-for-google-business'); ?></button>
                                <button type="button" class="button etn-egr-edit-cancel"><?php echo esc_html__('Cancel', 'etchenet-reviews-for-google-business'); ?></button>
                            </p>
                        </form>
                    </div>
                </div>
        </div>
        
        <?php
    }
}

