<?php
/**
 * Biscotti Shortcodes
 * 
 * WordPress shortcodes for:
 * - [biscotti_cookies] - Cookie table for privacy policy
 * - [biscotti_consent_link] - Link to reopen consent modal
 * - [biscotti_data_export] - User data export button
 * - [biscotti_impressum] - Legal Suite: Impressum from dashboard
 * - [biscotti_privacy_policy] - Legal Suite: Privacy policy from dashboard
 * - [biscotti_cookie_policy] - Legal Suite: Cookie policy from dashboard
 */

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

class Biscotti_Shortcodes
{

    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        add_shortcode('biscotti_cookies', [$this, 'render_cookie_table']);
        add_shortcode('biscotti_consent_link', [$this, 'render_consent_link']);
        add_shortcode('biscotti_settings_link', [$this, 'render_settings_link']); // Opens settings panel directly
        add_shortcode('biscotti_data_export', [$this, 'render_data_export']);
        add_shortcode('biscotti_do_not_sell', [$this, 'render_do_not_sell']);

        // Legal Suite shortcodes
        add_shortcode('biscotti_impressum', [$this, 'render_impressum']);
        add_shortcode('biscotti_privacy_policy', [$this, 'render_privacy_policy']);
        add_shortcode('biscotti_cookie_policy', [$this, 'render_cookie_policy']);

        // Custom Service Embed shortcode
        add_shortcode('biscotti_embed', [$this, 'render_embed']);

        // Generic document shortcode (used by "Assign to page" admin flow)
        add_shortcode('biscotti-document', [$this, 'render_biscotti_document']);

        // Allow data-biscotti-* attributes through wp_kses for frontend content (C8 fix)
        add_filter('wp_kses_allowed_html', [$this, 'allow_biscotti_data_attrs'], 10, 2);

        // Enqueue frontend CSS when shortcodes are used
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_styles']);
    }

    /**
     * Enqueue frontend styles for shortcodes
     */
    public function enqueue_frontend_styles()
    {
        // Never load frontend CSS on admin pages (C11 fix)
        if (is_admin()) {
            return;
        }

        wp_enqueue_style(
            'biscotti-frontend',
            BISCOTTI_PLUGIN_URL . 'assets/css/frontend.css',
            [],
            BISCOTTI_VERSION
        );
    }

    /**
     * Allow data-biscotti-* attributes through wp_kses for frontend content.
     * wp_kses does NOT expand 'data-*' wildcards, so each attribute must be listed explicitly.
     *
     * @param array  $allowed Allowed HTML tags and attributes
     * @param string $context The context (e.g., 'post')
     * @return array Modified allowed HTML
     */
    public function allow_biscotti_data_attrs($allowed, $context)
    {
        if ($context !== 'post') {
            return $allowed;
        }

        $biscotti_attrs = [
            'data-biscotti-service'  => true,
            'data-biscotti-category' => true,
            'data-biscotti-block'    => true,
            'data-biscotti-src'      => true,
            'data-biscotti-consent'  => true,
        ];

        foreach (['div', 'span', 'iframe', 'script', 'img', 'video', 'audio'] as $tag) {
            if (isset($allowed[$tag])) {
                $allowed[$tag] = array_merge($allowed[$tag], $biscotti_attrs);
            }
        }

        return $allowed;
    }

    /**
     * Render cookie table for privacy policy
     * 
     * Usage: [biscotti_cookies category="all|essential|functional|analytics|marketing"]
     */
    public function render_cookie_table($atts)
    {
        $atts = shortcode_atts([
            'category' => 'all',
            'show_duration' => 'true',
            'show_provider' => 'true',
            'lang' => '',
        ], $atts);

        $lang = !empty($atts['lang']) ? $atts['lang'] : Biscotti_Language_Bridge::get_current_language();
        $labels = $this->get_labels($lang);

        // Get cookies from scan or configuration
        $cookies = $this->get_configured_cookies($atts['category']);

        if (empty($cookies)) {
            return '<p>' . esc_html__('No cookies configured.', 'biscotti-cmp') . '</p>';
        }

        ob_start();
        ?>
        <div class="biscotti-cookie-table" id="biscotti-cookie-table">
            <?php foreach ($this->group_by_category($cookies) as $category => $cat_cookies): ?>
                <h4 class="biscotti-category-title">
                    <?php echo esc_html($this->get_category_name($category, $lang)); ?>
                </h4>
                <p class="biscotti-category-desc">
                    <?php echo esc_html($this->get_category_description($category, $lang)); ?>
                </p>

                <table class="biscotti-table">
                    <thead>
                        <tr>
                            <th>
                                <?php echo esc_html($labels['name']); ?>
                            </th>
                            <?php if ($atts['show_provider'] === 'true'): ?>
                                <th>
                                    <?php echo esc_html($labels['provider']); ?>
                                </th>
                            <?php endif; ?>
                            <th>
                                <?php echo esc_html($labels['purpose']); ?>
                            </th>
                            <?php if ($atts['show_duration'] === 'true'): ?>
                                <th>
                                    <?php echo esc_html($labels['duration']); ?>
                                </th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($cat_cookies as $cookie): ?>
                            <tr>
                                <td><code><?php echo esc_html($cookie['name']); ?></code></td>
                                <?php if ($atts['show_provider'] === 'true'): ?>
                                    <td>
                                        <?php echo esc_html($cookie['provider'] ?? '-'); ?>
                                    </td>
                                <?php endif; ?>
                                <td>
                                    <?php echo esc_html($cookie['description'] ?? $cookie['descriptionDe'] ?? '-'); ?>
                                </td>
                                <?php if ($atts['show_duration'] === 'true'): ?>
                                    <td>
                                        <?php echo esc_html($cookie['lifespan'] ?? $cookie['duration'] ?? '-'); ?>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endforeach; ?>

            <p class="biscotti-last-updated">
                <small>
                    <?php echo esc_html($labels['lastUpdated']); ?>:
                    <?php echo esc_html(date_i18n(get_option('date_format'))); ?>
                </small>
            </p>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render consent link to reopen modal
     * 
     * Usage: [biscotti_consent_link text="Change cookie settings" class="my-class"]
     */
    public function render_consent_link($atts)
    {
        $lang = Biscotti_Language_Bridge::get_current_language();
        $default_text = $this->get_labels($lang)['reopenConsent'];

        $atts = shortcode_atts([
            'text' => $default_text,
            'class' => 'biscotti-consent-link',
            'style' => '',
        ], $atts);

        return sprintf(
            '<a href="#" class="%s" style="%s" onclick="window.Biscotti && window.Biscotti.showBanner(); return false;">%s</a>',
            esc_attr($atts['class']),
            esc_attr($atts['style']),
            esc_html($atts['text'])
        );
    }

    /**
     * Render settings link to open settings panel directly (with granular options)
     * 
     * Usage: [biscotti_settings_link text="Change cookie settings" class="my-class"]
     */
    public function render_settings_link($atts)
    {
        $lang = Biscotti_Language_Bridge::get_current_language();
        $default_text = $this->get_labels($lang)['reopenConsent'];

        $atts = shortcode_atts([
            'text' => $default_text,
            'class' => 'biscotti-settings-link',
            'style' => '',
        ], $atts);

        return sprintf(
            '<a href="#" class="%s" style="%s" onclick="window.Biscotti && window.Biscotti.showSettings(); return false;">%s</a>',
            esc_attr($atts['class']),
            esc_attr($atts['style']),
            esc_html($atts['text'])
        );
    }

    /**
     * Render user data export form (GDPR Art. 15)
     * 
     * Usage: [biscotti_data_export]
     */
    public function render_data_export($atts)
    {
        $lang = Biscotti_Language_Bridge::get_current_language();
        $labels = $this->get_data_export_labels($lang);

        ob_start();
        ?>
        <div class="biscotti-data-export" id="biscotti-data-export">
            <h4>
                <?php echo esc_html($labels['title']); ?>
            </h4>
            <p>
                <?php echo esc_html($labels['description']); ?>
            </p>

            <button type="button" class="biscotti-export-btn" onclick="window.Biscotti && window.Biscotti.exportUserData()">
                <?php echo esc_html($labels['download']); ?>
            </button>

            <div id="biscotti-export-result" style="display:none; margin-top:16px;">
                <h5>
                    <?php echo esc_html__('Your stored data:', 'biscotti-cmp'); ?>
                </h5>
                <pre id="biscotti-export-data"
                    style="background:#f5f5f5; padding:16px; border-radius:8px; overflow:auto;"></pre>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render CCPA "Do Not Sell" link
     * 
     * Usage: [biscotti_do_not_sell]
     */
    public function render_do_not_sell($atts)
    {
        $lang = Biscotti_Language_Bridge::get_current_language();
        $labels = $this->get_ccpa_labels($lang);

        $atts = shortcode_atts([
            'text' => $labels['doNotSell'],
            'class' => 'biscotti-dns-link',
        ], $atts);

        ob_start();
        ?>
        <div class="biscotti-dns-container">
            <a href="#" class="<?php echo esc_attr($atts['class']); ?>"
                onclick="window.Biscotti && window.Biscotti.optOutSale(); return false;">
                <?php echo esc_html($atts['text']); ?>
            </a>
            <p class="biscotti-dns-desc">
                <?php echo esc_html($labels['doNotSellDesc']); ?>
            </p>
        </div>
        <?php
        return ob_get_clean();
    }

    // =========================================================================
    // CUSTOM SERVICE EMBED SHORTCODE
    // =========================================================================

    /**
     * Render custom service embed placeholder
     * 
     * Usage: [biscotti_embed service="wistia-video"]
     * 
     * Outputs a <div data-biscotti-service="X"></div> that biscotti.js
     * recognizes and blocks until consent is granted for the service's category.
     */
    public function render_embed($atts)
    {
        $atts = shortcode_atts([
            'service' => '',
            'class'   => 'biscotti-embed-container',
        ], $atts);

        $service_slug = sanitize_title($atts['service']);

        if (empty($service_slug)) {
            return '<!-- biscotti_embed: service attribute required -->';
        }

        return sprintf(
            '<div data-biscotti-service="%s" class="%s"></div>',
            esc_attr($service_slug),
            esc_attr($atts['class'])
        );
    }

    // =========================================================================
    // GENERIC DOCUMENT SHORTCODE (used by "Assign to page" admin flow)
    // =========================================================================

    /**
     * Render [biscotti-document type="..."] shortcode
     * Maps type attribute to existing legal document renderers.
     * This is the shortcode inserted by the "Assign to page" admin flow.
     *
     * Usage: [biscotti-document type="impressum" cache="true" class="my-class" lang="de"]
     */
    public function render_biscotti_document($atts)
    {
        $atts = shortcode_atts([
            'type'  => '',
            'cache' => 'true',
            'class' => 'biscotti-legal-document',
            'lang'  => '',
        ], $atts);

        $type = strtolower(trim($atts['type']));

        if (empty($type)) {
            return '<p class="biscotti-error">' . esc_html__('Document type not specified.', 'biscotti-cmp') . '</p>';
        }

        // Map type attribute to internal document type constants
        $type_map = [
            'impressum'      => 'IMPRESSUM',
            'privacy_policy' => 'PRIVACY_POLICY',
            'privacy-policy' => 'PRIVACY_POLICY',
            'cookie_policy'  => 'COOKIE_POLICY',
            'cookie-policy'  => 'COOKIE_POLICY',
            'agb'            => 'AGB',
            'terms'          => 'AGB',
        ];

        $doc_type = $type_map[$type] ?? strtoupper(str_replace('-', '_', $type));

        return $this->render_legal_document($doc_type, $atts);
    }

    // =========================================================================
    // LEGAL SUITE SHORTCODES
    // =========================================================================

    /**
     * Render Impressum from Legal Suite
     * 
     * Usage: [biscotti_impressum cache="true" class="my-impressum"]
     */
    public function render_impressum($atts)
    {
        return $this->render_legal_document('IMPRESSUM', $atts);
    }

    /**
     * Render Privacy Policy from Legal Suite
     * 
     * Usage: [biscotti_privacy_policy cache="true" class="my-privacy"]
     */
    public function render_privacy_policy($atts)
    {
        return $this->render_legal_document('PRIVACY_POLICY', $atts);
    }

    /**
     * Render Cookie Policy from Legal Suite
     * 
     * Usage: [biscotti_cookie_policy cache="true" class="my-cookies"]
     */
    public function render_cookie_policy($atts)
    {
        return $this->render_legal_document('COOKIE_POLICY', $atts);
    }

    /**
     * Generic renderer for legal documents
     * API-first: the Biscotti API is the single source of truth.
     * Local documents are only used as fallback when the API is unreachable.
     * When the API delivers a newer version, the local version is archived.
     */
    private function render_legal_document($type, $atts)
    {
        $atts = shortcode_atts([
            'cache' => 'true',
            'class' => 'biscotti-legal-document',
            'lang' => '',
        ], $atts);

        $lang = !empty($atts['lang']) ? $atts['lang'] : Biscotti_Language_Bridge::get_current_language();

        // Map type to storage key
        $type_map = [
            'IMPRESSUM' => 'impressum',
            'PRIVACY_POLICY' => 'privacy_policy',
            'COOKIE_POLICY' => 'cookie_policy',
        ];
        $storage_key = $type_map[$type] ?? strtolower($type);

        $options = get_option('biscotti_options', []);
        $api_key = $options['api_key'] ?? '';
        $website_id = $options['website_id'] ?? '';

        // =====================================================================
        // 1. TRY API FIRST (Single Source of Truth)
        // =====================================================================
        if (!empty($website_id)) {
            // Check transient cache first
            $cache_key = 'biscotti_legal_' . md5($type . $website_id . $lang);
            $cached = $atts['cache'] === 'true' ? get_transient($cache_key) : false;

            if ($cached !== false && is_array($cached)) {
                // Cached API response
                return $this->render_api_document($cached, esc_attr($atts['class']), $type);
            }

            // Fetch fresh from API
            $api_doc = $this->fetch_legal_document_with_meta($api_key, $website_id, $type, $lang);

            if ($api_doc !== false) {
                // Archive old local version if API has a newer one
                $this->maybe_archive_local($storage_key, $api_doc);

                // Update local cache with API version
                $this->update_local_cache($storage_key, $api_doc);

                // Cache for 1 hour
                if ($atts['cache'] === 'true') {
                    set_transient($cache_key, $api_doc, HOUR_IN_SECONDS);
                }

                return $this->render_api_document($api_doc, esc_attr($atts['class']), $type);
            }
        }

        // =====================================================================
        // 2. FALLBACK: Local documents (only if API unreachable)
        // =====================================================================
        $local_documents = get_option('biscotti_legal_documents', []);
        if (!empty($local_documents[$storage_key]['content'])) {
            $status = $local_documents[$storage_key]['status'] ?? 'draft';
            if ($status === 'draft') {
                return '<div class="biscotti-draft-notice" style="padding:16px;background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;color:#92400e;">' .
                    '<strong>📝 ' . esc_html__('Draft', 'biscotti-cmp') . '</strong> — ' .
                    esc_html__('This document has not been published yet.', 'biscotti-cmp') .
                    '</div>';
            }
            if ($status === 'published') {
                return $this->wrap_legal_content($local_documents[$storage_key]['content'], esc_attr($atts['class']), $type);
            }
            return '';
        }

        // =====================================================================
        // 3. NO DOCUMENT FOUND
        // =====================================================================
        if (empty($website_id)) {
            return '<p class="biscotti-error">' . esc_html__('Please generate this document first in the Legal Suite.', 'biscotti-cmp') . '</p>';
        }
        return '<p class="biscotti-error">' . esc_html__('Document not found. Please generate it in the Legal Suite.', 'biscotti-cmp') . '</p>';
    }

    /**
     * Render a document from API response data
     */
    private function render_api_document($doc, $class, $type)
    {
        $status = $doc['status'] ?? 'PUBLISHED';

        // Draft documents show a notice instead of content
        if (strtoupper($status) === 'DRAFT') {
            return '<div class="biscotti-draft-notice" style="padding:16px;background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;color:#92400e;">' .
                '<strong>📝 ' . esc_html__('Draft', 'biscotti-cmp') . '</strong> — ' .
                esc_html__('This document has not been published yet.', 'biscotti-cmp') .
                '</div>';
        }

        // Deactivated documents show nothing
        if (strtoupper($status) === 'DEACTIVATED' || strtoupper($status) === 'ARCHIVED') {
            return '';
        }

        $content = $doc['content'] ?? $doc['contentHtml'] ?? '';
        if (empty($content)) {
            return '';
        }

        return $this->wrap_legal_content($content, $class, $type);
    }

    /**
     * Archive old local document if API delivers a newer version
     */
    private function maybe_archive_local($storage_key, $api_doc)
    {
        $local_documents = get_option('biscotti_legal_documents', []);
        if (empty($local_documents[$storage_key]['content'])) {
            return; // Nothing to archive
        }

        $local_updated = $local_documents[$storage_key]['updatedAt'] ?? '';
        $api_updated = $api_doc['updatedAt'] ?? '';

        // Archive if API is newer or if updatedAt comparison isn't possible
        $should_archive = true;
        if ($local_updated && $api_updated) {
            $should_archive = strtotime($api_updated) > strtotime($local_updated);
        }

        if ($should_archive) {
            // Move to archive
            $archive = get_option('biscotti_legal_archive', []);
            if (!isset($archive[$storage_key])) {
                $archive[$storage_key] = [];
            }

            // Add timestamp to archived version
            $archived_doc = $local_documents[$storage_key];
            $archived_doc['archivedAt'] = current_time('mysql');
            $archive[$storage_key][] = $archived_doc;

            // Keep only last 10 versions per document type
            if (count($archive[$storage_key]) > 10) {
                $archive[$storage_key] = array_slice($archive[$storage_key], -10);
            }

            update_option('biscotti_legal_archive', $archive);

            // Remove from active local documents
            unset($local_documents[$storage_key]);
            update_option('biscotti_legal_documents', $local_documents);
        }
    }

    /**
     * Update local cache with API document data
     */
    private function update_local_cache($storage_key, $api_doc)
    {
        $local_documents = get_option('biscotti_legal_documents', []);
        $local_documents[$storage_key] = [
            'content' => $api_doc['content'] ?? $api_doc['contentHtml'] ?? '',
            'status' => strtolower($api_doc['status'] ?? 'published'),
            'updatedAt' => $api_doc['updatedAt'] ?? current_time('mysql'),
            'source' => 'api',
        ];
        update_option('biscotti_legal_documents', $local_documents);
    }

    /**
     * Fetch legal document from Biscotti API with full metadata
     * Returns document data array or false on failure
     */
    private function fetch_legal_document_with_meta($api_key, $website_id, $type, $lang)
    {
        $custom_url = get_option('biscotti_cmp_api_url', '');
        $api_url = !empty($custom_url) ? rtrim($custom_url, '/') . '/api/v1' : 'https://api.biscotti-cmp.com/api/v1';

        $headers = [
            'X-Website-ID' => $website_id,
            'Accept' => 'application/json',
            'Accept-Language' => $lang,
        ];
        if (!empty($api_key)) {
            $headers['X-API-Key'] = $api_key;
        }

        $response = wp_remote_get($api_url . '/legal/documents', [
            'timeout' => 10,
            'headers' => $headers,
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (!$data || !isset($data['success']) || $data['success'] !== true) {
            return false;
        }

        // Find matching document — return full metadata
        $docs = $data['data'] ?? [];
        foreach ($docs as $doc) {
            if (($doc['type'] ?? '') === $type && ($doc['language'] ?? 'en') === $lang) {
                return $doc;
            }
        }

        return false;
    }

    /**
     * Wrap legal content with container and styles
     */
    private function wrap_legal_content($content, $class, $type)
    {
        $type_slug = strtolower(str_replace('_', '-', $type));

        ob_start();
        ?>
        <div class="<?php echo esc_attr($class); ?> biscotti-legal-content biscotti-legal-<?php echo esc_attr($type_slug); ?>">
            <?php echo wp_kses_post($content); ?>
        </div>
        <?php
        return ob_get_clean();
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    /**
     * Get configured cookies from options or API
     */
    private function get_configured_cookies($category = 'all')
    {
        $options = get_option('biscotti_settings', []);
        $cookies = $options['cookies'] ?? [];

        // If no cookies configured, try to get from last scan
        if (empty($cookies)) {
            $last_scan = get_option('biscotti_last_scan', []);
            $cookies = $last_scan['cookies'] ?? [];
        }

        // Filter by category if specified
        if ($category !== 'all') {
            $category_upper = strtoupper($category);
            $cookies = array_filter($cookies, function ($c) use ($category_upper) {
                return strtoupper($c['category'] ?? '') === $category_upper;
            });
        }

        return $cookies;
    }

    /**
     * Group cookies by category
     */
    private function group_by_category($cookies)
    {
        $grouped = [
            'essential' => [],
            'functional' => [],
            'analytics' => [],
            'marketing' => [],
        ];

        foreach ($cookies as $cookie) {
            $cat = strtolower($cookie['category'] ?? 'marketing');
            if (!isset($grouped[$cat])) {
                $cat = 'marketing'; // Default to most restrictive
            }
            $grouped[$cat][] = $cookie;
        }

        // Remove empty categories
        return array_filter($grouped);
    }

    /**
     * Get localized labels for cookie table
     */
    private function get_labels($lang)
    {
        $lang = Biscotti_Languages::to_legacy($lang);
        $labels = [
            'de' => ['name' => 'Cookie name', 'provider' => 'Provider', 'purpose' => 'Zweck', 'duration' => 'Speicherdauer', 'lastUpdated' => 'Zuletzt aktualisiert', 'reopenConsent' => 'Cookie-Einstellungen ändern'],
            'en' => ['name' => 'Cookie Name', 'provider' => 'Provider', 'purpose' => 'Purpose', 'duration' => 'Duration', 'lastUpdated' => 'Last updated', 'reopenConsent' => 'Change cookie settings'],
            'fr' => ['name' => 'Nom du cookie', 'provider' => 'Fournisseur', 'purpose' => 'Finalité', 'duration' => 'Durée', 'lastUpdated' => 'Dernière mise à jour', 'reopenConsent' => 'Modifier les paramètres de cookies'],
            'es' => ['name' => 'Nombre de la cookie', 'provider' => 'Proveedor', 'purpose' => 'Propósito', 'duration' => 'Duración', 'lastUpdated' => 'Última actualización', 'reopenConsent' => 'Cambiar configuración de cookies'],
            'it' => ['name' => 'Nome cookie', 'provider' => 'Fornitore', 'purpose' => 'Scopo', 'duration' => 'Durata', 'lastUpdated' => 'Ultimo aggiornamento', 'reopenConsent' => 'Modifica impostazioni cookie'],
            'nl' => ['name' => 'Cookienaam', 'provider' => 'Aanbieder', 'purpose' => 'Doel', 'duration' => 'Bewaartermijn', 'lastUpdated' => 'Laatst bijgewerkt', 'reopenConsent' => 'Cookie-instellingen wijzigen'],
            'pl' => ['name' => 'Nazwa pliku cookie', 'provider' => 'Dostawca', 'purpose' => 'Cel', 'duration' => 'Czas przechowywania', 'lastUpdated' => 'Ostatnia aktualizacja', 'reopenConsent' => 'Zmień ustawienia plików cookie'],
            'pt' => ['name' => 'Nome do cookie', 'provider' => 'Fornecedor', 'purpose' => 'Finalidade', 'duration' => 'Duração', 'lastUpdated' => 'Última atualização', 'reopenConsent' => 'Alterar definições de cookies'],
            'da' => ['name' => 'Cookienavn', 'provider' => 'Udbyder', 'purpose' => 'Formål', 'duration' => 'Varighed', 'lastUpdated' => 'Sidst opdateret', 'reopenConsent' => 'Ændre cookieindstillinger'],
            'sv' => ['name' => 'Cookienamn', 'provider' => 'Leverantör', 'purpose' => 'Syfte', 'duration' => 'Lagringstid', 'lastUpdated' => 'Senast uppdaterad', 'reopenConsent' => 'Ändra cookieinställningar'],
            'fi' => ['name' => 'Evästeen nimi', 'provider' => 'Tarjoaja', 'purpose' => 'Tarkoitus', 'duration' => 'Kesto', 'lastUpdated' => 'Viimeksi päivitetty', 'reopenConsent' => 'Muuta evästeasetuksia'],
            'no' => ['name' => 'Informasjonskapsel', 'provider' => 'Leverandør', 'purpose' => 'Formål', 'duration' => 'Varighet', 'lastUpdated' => 'Sist oppdatert', 'reopenConsent' => 'Endre innstillinger for informasjonskapsler'],
            'cs' => ['name' => 'Název cookie', 'provider' => 'Poskytovatel', 'purpose' => 'Účel', 'duration' => 'Doba uložení', 'lastUpdated' => 'Naposledy aktualizováno', 'reopenConsent' => 'Změnit nastavení cookies'],
            'sk' => ['name' => 'Názov cookie', 'provider' => 'Poskytovateľ', 'purpose' => 'Účel', 'duration' => 'Doba uloženia', 'lastUpdated' => 'Naposledy aktualizované', 'reopenConsent' => 'Zmeniť nastavenia cookies'],
            'hu' => ['name' => 'Cookie neve', 'provider' => 'Szolgáltató', 'purpose' => 'Cél', 'duration' => 'Tárolási idő', 'lastUpdated' => 'Utoljára frissítve', 'reopenConsent' => 'Cookie-beállítások módosítása'],
            'ro' => ['name' => 'Numele cookie', 'provider' => 'Furnizor', 'purpose' => 'Scop', 'duration' => 'Durată', 'lastUpdated' => 'Ultima actualizare', 'reopenConsent' => 'Modificați setările cookie'],
            'el' => ['name' => 'Όνομα cookie', 'provider' => 'Πάροχος', 'purpose' => 'Σκοπός', 'duration' => 'Διάρκεια', 'lastUpdated' => 'Τελευταία ενημέρωση', 'reopenConsent' => 'Αλλαγή ρυθμίσεων cookie'],
            'hr' => ['name' => 'Naziv kolačića', 'provider' => 'Pružatelj', 'purpose' => 'Svrha', 'duration' => 'Trajanje', 'lastUpdated' => 'Zadnje ažuriranje', 'reopenConsent' => 'Promijeni postavke kolačića'],
            'bg' => ['name' => 'Име на бисквитката', 'provider' => 'Доставчик', 'purpose' => 'Цел', 'duration' => 'Продължителност', 'lastUpdated' => 'Последна актуализация', 'reopenConsent' => 'Промяна на настройките за бисквитки'],
            'sl' => ['name' => 'Ime piškotka', 'provider' => 'Ponudnik', 'purpose' => 'Namen', 'duration' => 'Trajanje', 'lastUpdated' => 'Nazadnje posodobljeno', 'reopenConsent' => 'Spremeni nastavitve piškotkov'],
            'et' => ['name' => 'Küpsise nimi', 'provider' => 'Pakkuja', 'purpose' => 'Eesmärk', 'duration' => 'Kestus', 'lastUpdated' => 'Viimati uuendatud', 'reopenConsent' => 'Muuda küpsiste seadeid'],
            'lv' => ['name' => 'Sīkdatnes nosaukums', 'provider' => 'Pakalpojuma sniedzējs', 'purpose' => 'Mērķis', 'duration' => 'Ilgums', 'lastUpdated' => 'Pēdējoreiz atjaunināts', 'reopenConsent' => 'Mainīt sīkdatņu iestatījumus'],
            'lt' => ['name' => 'Slapuko pavadinimas', 'provider' => 'Teikėjas', 'purpose' => 'Tikslas', 'duration' => 'Trukmė', 'lastUpdated' => 'Paskutinį kartą atnaujinta', 'reopenConsent' => 'Keisti slapukų nustatymus'],
            'ja' => ['name' => 'Cookie名', 'provider' => 'プロバイダー', 'purpose' => '目的', 'duration' => '保存期間', 'lastUpdated' => '最終更新日', 'reopenConsent' => 'Cookie設定を変更'],
            'ko' => ['name' => '쿠키 이름', 'provider' => '제공자', 'purpose' => '목적', 'duration' => '저장 기간', 'lastUpdated' => '최종 업데이트', 'reopenConsent' => '쿠키 설정 변경'],
            'zh' => ['name' => 'Cookie 名称', 'provider' => '提供者', 'purpose' => '用途', 'duration' => '存储时长', 'lastUpdated' => '上次更新', 'reopenConsent' => '更改 Cookie 设置'],
            'ar' => ['name' => 'اسم ملف تعريف الارتباط', 'provider' => 'المزود', 'purpose' => 'الغرض', 'duration' => 'المدة', 'lastUpdated' => 'آخر تحديث', 'reopenConsent' => 'تغيير إعدادات ملفات تعريف الارتباط'],
            'he' => ['name' => 'שם העוגייה', 'provider' => 'ספק', 'purpose' => 'מטרה', 'duration' => 'משך', 'lastUpdated' => 'עודכן לאחרונה', 'reopenConsent' => 'שנה הגדרות עוגיות'],
            'hi' => ['name' => 'कुकी का नाम', 'provider' => 'प्रदाता', 'purpose' => 'उद्देश्य', 'duration' => 'अवधि', 'lastUpdated' => 'अंतिम अपडेट', 'reopenConsent' => 'कुकी सेटिंग्स बदलें'],
            'th' => ['name' => 'ชื่อคุกกี้', 'provider' => 'ผู้ให้บริการ', 'purpose' => 'วัตถุประสงค์', 'duration' => 'ระยะเวลา', 'lastUpdated' => 'อัปเดตล่าสุด', 'reopenConsent' => 'เปลี่ยนการตั้งค่าคุกกี้'],
            'vi' => ['name' => 'Tên cookie', 'provider' => 'Nhà cung cấp', 'purpose' => 'Mục đích', 'duration' => 'Thời hạn', 'lastUpdated' => 'Cập nhật lần cuối', 'reopenConsent' => 'Thay đổi cài đặt cookie'],
            'id' => ['name' => 'Nama cookie', 'provider' => 'Penyedia', 'purpose' => 'Tujuan', 'duration' => 'Durasi', 'lastUpdated' => 'Terakhir diperbarui', 'reopenConsent' => 'Ubah pengaturan cookie'],
            'ms' => ['name' => 'Nama kuki', 'provider' => 'Pembekal', 'purpose' => 'Tujuan', 'duration' => 'Tempoh', 'lastUpdated' => 'Kemas kini terakhir', 'reopenConsent' => 'Tukar tetapan kuki'],
            'tr' => ['name' => 'Çerez adı', 'provider' => 'Sağlayıcı', 'purpose' => 'Amaç', 'duration' => 'Süre', 'lastUpdated' => 'Son güncelleme', 'reopenConsent' => 'Çerez ayarlarını değiştir'],
            'uk' => ['name' => 'Назва cookie', 'provider' => 'Постачальник', 'purpose' => 'Мета', 'duration' => 'Тривалість', 'lastUpdated' => 'Останнє оновлення', 'reopenConsent' => 'Змінити налаштування cookie'],
            'sr' => ['name' => 'Naziv kolačića', 'provider' => 'Pružalac', 'purpose' => 'Svrha', 'duration' => 'Trajanje', 'lastUpdated' => 'Poslednje ažuriranje', 'reopenConsent' => 'Promenite podešavanja kolačića'],
            'ka' => ['name' => 'ქუქის სახელი', 'provider' => 'პროვაიდერი', 'purpose' => 'მიზანი', 'duration' => 'ხანგრძლივობა', 'lastUpdated' => 'ბოლო განახლება', 'reopenConsent' => 'ქუქის პარამეტრების შეცვლა'],
            'sw' => ['name' => 'Jina la kuki', 'provider' => 'Mtoa huduma', 'purpose' => 'Madhumuni', 'duration' => 'Muda', 'lastUpdated' => 'Ilisasishwa mwisho', 'reopenConsent' => 'Badilisha mipangilio ya kuki'],
            'ga' => ['name' => 'Ainm an fhianáin', 'provider' => 'Soláthraí', 'purpose' => 'Cuspóir', 'duration' => 'Fad', 'lastUpdated' => 'Nuashonraithe go deireanach', 'reopenConsent' => 'Athraigh socruithe fianán'],
            'ru' => ['name' => 'Имя cookie', 'provider' => 'Поставщик', 'purpose' => 'Цель', 'duration' => 'Срок хранения', 'lastUpdated' => 'Последнее обновление', 'reopenConsent' => 'Изменить настройки cookie'],
            'bs' => ['name' => 'Naziv kolačića', 'provider' => 'Pružalac', 'purpose' => 'Svrha', 'duration' => 'Trajanje', 'lastUpdated' => 'Posljednje ažuriranje', 'reopenConsent' => 'Promijeni postavke kolačića'],
            'ca' => ['name' => 'Nom de la galeta', 'provider' => 'Proveïdor', 'purpose' => 'Finalitat', 'duration' => 'Durada', 'lastUpdated' => 'Darrera actualització', 'reopenConsent' => 'Canviar la configuració de les galetes'],
            'eu' => ['name' => 'Cookie-aren izena', 'provider' => 'Hornitzailea', 'purpose' => 'Helburua', 'duration' => 'Iraupena', 'lastUpdated' => 'Azken eguneraketa', 'reopenConsent' => 'Aldatu cookie-en ezarpenak'],
            'gl' => ['name' => 'Nome da cookie', 'provider' => 'Provedor', 'purpose' => 'Finalidade', 'duration' => 'Duración', 'lastUpdated' => 'Última actualización', 'reopenConsent' => 'Cambiar a configuración das cookies'],
            'mr' => ['name' => 'कुकीचे नाव', 'provider' => 'प्रदाता', 'purpose' => 'उद्देश', 'duration' => 'कालावधी', 'lastUpdated' => 'शेवटचे अपडेट', 'reopenConsent' => 'कुकी सेटिंग्ज बदला'],
        ];

        return $labels[$lang] ?? $labels['en'];
    }

    /**
     * Get category name by language
     */
    private function get_category_name($category, $lang)
    {
        $lang = Biscotti_Languages::to_legacy($lang);
        $names = [
            'de' => ['essential' => 'Notwendige Cookies', 'functional' => 'Funktionale Cookies', 'analytics' => 'Statistik-Cookies', 'marketing' => 'Marketing-Cookies'],
            'en' => ['essential' => 'Essential Cookies', 'functional' => 'Functional Cookies', 'analytics' => 'Analytics Cookies', 'marketing' => 'Marketing Cookies'],
            'fr' => ['essential' => 'Cookies essentiels', 'functional' => 'Cookies fonctionnels', 'analytics' => 'Cookies statistiques', 'marketing' => 'Cookies marketing'],
            'es' => ['essential' => 'Cookies esenciales', 'functional' => 'Cookies funcionales', 'analytics' => 'Cookies de estadísticas', 'marketing' => 'Cookies de marketing'],
            'it' => ['essential' => 'Cookie essenziali', 'functional' => 'Cookie funzionali', 'analytics' => 'Cookie statistici', 'marketing' => 'Cookie marketing'],
            'nl' => ['essential' => 'Noodzakelijke cookies', 'functional' => 'Functionele cookies', 'analytics' => 'Statistiek cookies', 'marketing' => 'Marketing cookies'],
            'pl' => ['essential' => 'Niezbędne cookies', 'functional' => 'Funkcjonalne cookies', 'analytics' => 'Statystyczne cookies', 'marketing' => 'Marketingowe cookies'],
            'pt' => ['essential' => 'Cookies essenciais', 'functional' => 'Cookies funcionais', 'analytics' => 'Cookies de estatísticas', 'marketing' => 'Cookies de marketing'],
            'da' => ['essential' => 'Nødvendige cookies', 'functional' => 'Funktionelle cookies', 'analytics' => 'Statistik cookies', 'marketing' => 'Marketing cookies'],
            'sv' => ['essential' => 'Nödvändiga cookies', 'functional' => 'Funktionella cookies', 'analytics' => 'Statistik-cookies', 'marketing' => 'Marknadsföringscookies'],
            'fi' => ['essential' => 'Välttämättömät evästeet', 'functional' => 'Toiminnalliset evästeet', 'analytics' => 'Tilastoevästeet', 'marketing' => 'Markkinointievästeet'],
            'no' => ['essential' => 'Nødvendige informasjonskapsler', 'functional' => 'Funksjonelle informasjonskapsler', 'analytics' => 'Statistiske informasjonskapsler', 'marketing' => 'Markedsføringskapsler'],
            'cs' => ['essential' => 'Nezbytné cookies', 'functional' => 'Funkční cookies', 'analytics' => 'Statistické cookies', 'marketing' => 'Marketingové cookies'],
            'sk' => ['essential' => 'Nevyhnutné cookies', 'functional' => 'Funkčné cookies', 'analytics' => 'Štatistické cookies', 'marketing' => 'Marketingové cookies'],
            'hu' => ['essential' => 'Szükséges sütik', 'functional' => 'Funkcionális sütik', 'analytics' => 'Statisztikai sütik', 'marketing' => 'Marketing sütik'],
            'ro' => ['essential' => 'Cookie-uri esențiale', 'functional' => 'Cookie-uri funcționale', 'analytics' => 'Cookie-uri de statistică', 'marketing' => 'Cookie-uri de marketing'],
            'el' => ['essential' => 'Απαραίτητα cookies', 'functional' => 'Λειτουργικά cookies', 'analytics' => 'Στατιστικά cookies', 'marketing' => 'Cookies μάρκετινγκ'],
            'hr' => ['essential' => 'Neophodni kolačići', 'functional' => 'Funkcionalni kolačići', 'analytics' => 'Statistički kolačići', 'marketing' => 'Marketinški kolačići'],
            'bg' => ['essential' => 'Необходими бисквитки', 'functional' => 'Функционални бисквитки', 'analytics' => 'Статистически бисквитки', 'marketing' => 'Маркетингови бисквитки'],
            'sl' => ['essential' => 'Nujni piškotki', 'functional' => 'Funkcionalni piškotki', 'analytics' => 'Statistični piškotki', 'marketing' => 'Trženjski piškotki'],
            'et' => ['essential' => 'Vajalikud küpsised', 'functional' => 'Funktsionaalsed küpsised', 'analytics' => 'Statistilised küpsised', 'marketing' => 'Turundusküpsised'],
            'lv' => ['essential' => 'Nepieciešamās sīkdatnes', 'functional' => 'Funkcionālās sīkdatnes', 'analytics' => 'Statistikas sīkdatnes', 'marketing' => 'Mārketinga sīkdatnes'],
            'lt' => ['essential' => 'Būtini slapukai', 'functional' => 'Funkciniai slapukai', 'analytics' => 'Statistiniai slapukai', 'marketing' => 'Rinkodaros slapukai'],
            'ja' => ['essential' => '必須Cookie', 'functional' => '機能Cookie', 'analytics' => '統計Cookie', 'marketing' => 'マーケティングCookie'],
            'ko' => ['essential' => '필수 쿠키', 'functional' => '기능 쿠키', 'analytics' => '통계 쿠키', 'marketing' => '마케팅 쿠키'],
            'zh' => ['essential' => '必要 Cookie', 'functional' => '功能 Cookie', 'analytics' => '统计 Cookie', 'marketing' => '营销 Cookie'],
            'ar' => ['essential' => 'ملفات تعريف الارتباط الضرورية', 'functional' => 'ملفات تعريف الارتباط الوظيفية', 'analytics' => 'ملفات تعريف الارتباط الإحصائية', 'marketing' => 'ملفات تعريف الارتباط التسويقية'],
            'he' => ['essential' => 'עוגיות חיוניות', 'functional' => 'עוגיות פונקציונליות', 'analytics' => 'עוגיות סטטיסטיות', 'marketing' => 'עוגיות שיווקיות'],
            'hi' => ['essential' => 'आवश्यक कुकीज़', 'functional' => 'कार्यात्मक कुकीज़', 'analytics' => 'सांख्यिकीय कुकीज़', 'marketing' => 'विपणन कुकीज़'],
            'th' => ['essential' => 'คุกกี้ที่จำเป็น', 'functional' => 'คุกกี้เชิงฟังก์ชัน', 'analytics' => 'คุกกี้สถิติ', 'marketing' => 'คุกกี้การตลาด'],
            'vi' => ['essential' => 'Cookie thiết yếu', 'functional' => 'Cookie chức năng', 'analytics' => 'Cookie thống kê', 'marketing' => 'Cookie tiếp thị'],
            'id' => ['essential' => 'Cookie penting', 'functional' => 'Cookie fungsional', 'analytics' => 'Cookie statistik', 'marketing' => 'Cookie pemasaran'],
            'ms' => ['essential' => 'Kuki penting', 'functional' => 'Kuki berfungsi', 'analytics' => 'Kuki statistik', 'marketing' => 'Kuki pemasaran'],
            'tr' => ['essential' => 'Gerekli çerezler', 'functional' => 'İşlevsel çerezler', 'analytics' => 'İstatistik çerezler', 'marketing' => 'Pazarlama çerezleri'],
            'uk' => ['essential' => 'Необхідні cookie', 'functional' => 'Функціональні cookie', 'analytics' => 'Статистичні cookie', 'marketing' => 'Маркетингові cookie'],
            'sr' => ['essential' => 'Neophodni kolačići', 'functional' => 'Funkcionalni kolačići', 'analytics' => 'Statistički kolačići', 'marketing' => 'Marketinški kolačići'],
            'ka' => ['essential' => 'აუცილებელი ქუქები', 'functional' => 'ფუნქციური ქუქები', 'analytics' => 'სტატისტიკური ქუქები', 'marketing' => 'მარკეტინგული ქუქები'],
            'sw' => ['essential' => 'Kuki muhimu', 'functional' => 'Kuki za utendaji', 'analytics' => 'Kuki za takwimu', 'marketing' => 'Kuki za masoko'],
            'ga' => ['essential' => 'Fianáin riachtanacha', 'functional' => 'Fianáin fheidhmiúla', 'analytics' => 'Fianáin staitistice', 'marketing' => 'Fianáin mhargaíochta'],
            'ru' => ['essential' => 'Необходимые cookie', 'functional' => 'Функциональные cookie', 'analytics' => 'Статистические cookie', 'marketing' => 'Маркетинговые cookie'],
            'bs' => ['essential' => 'Neophodni kolačići', 'functional' => 'Funkcionalni kolačići', 'analytics' => 'Statistički kolačići', 'marketing' => 'Marketinški kolačići'],
            'ca' => ['essential' => 'Galetes essencials', 'functional' => 'Galetes funcionals', 'analytics' => 'Galetes estadístiques', 'marketing' => 'Galetes de màrqueting'],
            'eu' => ['essential' => 'Beharrezko cookieak', 'functional' => 'Cookie funtzionalak', 'analytics' => 'Estatistika cookieak', 'marketing' => 'Marketing cookieak'],
            'gl' => ['essential' => 'Cookies esenciais', 'functional' => 'Cookies funcionais', 'analytics' => 'Cookies de estatísticas', 'marketing' => 'Cookies de mercadotecnia'],
            'mr' => ['essential' => 'आवश्यक कुकीज', 'functional' => 'कार्यात्मक कुकीज', 'analytics' => 'सांख्यिकी कुकीज', 'marketing' => 'विपणन कुकीज'],
        ];

        $lang_names = $names[$lang] ?? $names['en'];
        return $lang_names[$category] ?? ucfirst($category);
    }

    /**
     * Get category description by language
     */
    private function get_category_description($category, $lang)
    {
        $lang = Biscotti_Languages::to_legacy($lang);
        $descriptions = [
            'de' => ['essential' => 'Diese Cookies sind für die Grundfunktionen der Website erforderlich und können nicht deaktiviert werden.', 'functional' => 'Diese Cookies ermöglichen erweiterte Funktionen und Personalisierung.', 'analytics' => 'Diese Cookies helfen uns, die Nutzung unserer Website zu verstehen und zu verbessern.', 'marketing' => 'Diese Cookies werden für Werbezwecke und zur Nachverfolgung über Websites hinweg verwendet.'],
            'en' => ['essential' => 'These cookies are required for basic website functionality and cannot be disabled.', 'functional' => 'These cookies enable enhanced functionality and personalization.', 'analytics' => 'These cookies help us understand and improve how our website is used.', 'marketing' => 'These cookies are used for advertising and to track visitors across websites.'],
            'fr' => ['essential' => 'Ces cookies sont nécessaires au fonctionnement de base du site et ne peuvent pas être désactivés.', 'functional' => 'Ces cookies permettent des fonctionnalités avancées et la personnalisation.', 'analytics' => 'Ces cookies nous aident à comprendre et améliorer l\'utilisation de notre site.', 'marketing' => 'Ces cookies sont utilisés à des fins publicitaires et pour suivre les visiteurs sur les sites.'],
            'es' => ['essential' => 'Estas cookies son necesarias para la funcionalidad básica del sitio y no pueden desactivarse.', 'functional' => 'Estas cookies permiten funcionalidades avanzadas y personalización.', 'analytics' => 'Estas cookies nos ayudan a comprender y mejorar el uso de nuestro sitio.', 'marketing' => 'Estas cookies se utilizan para publicidad y seguimiento de visitantes en sitios web.'],
            'it' => ['essential' => 'Questi cookie sono necessari per le funzionalità di base del sito e non possono essere disattivati.', 'functional' => 'Questi cookie consentono funzionalità avanzate e personalizzazione.', 'analytics' => 'Questi cookie ci aiutano a capire e migliorare l\'utilizzo del nostro sito.', 'marketing' => 'Questi cookie vengono utilizzati per scopi pubblicitari e per tracciare i visitatori sui siti web.'],
            'nl' => ['essential' => 'Deze cookies zijn noodzakelijk voor basisfunctionaliteit en kunnen niet worden uitgeschakeld.', 'functional' => 'Deze cookies maken geavanceerde functionaliteit en personalisatie mogelijk.', 'analytics' => 'Deze cookies helpen ons het gebruik van onze website te begrijpen en te verbeteren.', 'marketing' => 'Deze cookies worden gebruikt voor advertenties en om bezoekers op websites te volgen.'],
            'pl' => ['essential' => 'Te pliki cookie są niezbędne do podstawowego funkcjonowania strony i nie można ich wyłączyć.', 'functional' => 'Te pliki cookie umożliwiają zaawansowane funkcje i personalizację.', 'analytics' => 'Te pliki cookie pomagają nam zrozumieć i poprawić wykorzystanie naszej strony.', 'marketing' => 'Te pliki cookie są używane do celów reklamowych i śledzenia odwiedzających.'],
            'pt' => ['essential' => 'Estes cookies são necessários para a funcionalidade básica do site e não podem ser desativados.', 'functional' => 'Estes cookies permitem funcionalidades avançadas e personalização.', 'analytics' => 'Estes cookies ajudam-nos a compreender e melhorar a utilização do nosso site.', 'marketing' => 'Estes cookies são utilizados para fins publicitários e para rastrear visitantes em sites.'],
            'da' => ['essential' => 'Disse cookies er nødvendige for hjemmesidens grundlæggende funktionalitet og kan ikke deaktiveres.', 'functional' => 'Disse cookies muliggør avancerede funktioner og personalisering.', 'analytics' => 'Disse cookies hjælper os med at forstå og forbedre brugen af vores hjemmeside.', 'marketing' => 'Disse cookies bruges til reklameformål og til at spore besøgende på tværs af hjemmesider.'],
            'sv' => ['essential' => 'Dessa cookies krävs för webbplatsens grundläggande funktionalitet och kan inte inaktiveras.', 'functional' => 'Dessa cookies möjliggör utökad funktionalitet och anpassning.', 'analytics' => 'Dessa cookies hjälper oss att förstå och förbättra hur vår webbplats används.', 'marketing' => 'Dessa cookies används för reklam och för att spåra besökare på webbplatser.'],
            'fi' => ['essential' => 'Nämä evästeet ovat välttämättömiä verkkosivuston perustoiminnalle eikä niitä voi poistaa käytöstä.', 'functional' => 'Nämä evästeet mahdollistavat parannetut toiminnot ja personoinnin.', 'analytics' => 'Nämä evästeet auttavat meitä ymmärtämään ja parantamaan verkkosivustomme käyttöä.', 'marketing' => 'Näitä evästeitä käytetään mainontaan ja kävijöiden seurantaan verkkosivustoilla.'],
            'no' => ['essential' => 'Disse informasjonskapslene er nødvendige for nettstedets grunnleggende funksjonalitet og kan ikke deaktiveres.', 'functional' => 'Disse informasjonskapslene muliggjør utvidede funksjoner og personalisering.', 'analytics' => 'Disse informasjonskapslene hjelper oss å forstå og forbedre bruken av nettstedet.', 'marketing' => 'Disse informasjonskapslene brukes til reklameformål og for å spore besøkende på nettsteder.'],
            'cs' => ['essential' => 'Tyto cookies jsou nezbytné pro základní funkčnost webu a nelze je deaktivovat.', 'functional' => 'Tyto cookies umožňují pokročilé funkce a personalizaci.', 'analytics' => 'Tyto cookies nám pomáhají pochopit a zlepšit využití našeho webu.', 'marketing' => 'Tyto cookies slouží k reklamním účelům a sledování návštěvníků na webech.'],
            'sk' => ['essential' => 'Tieto cookies sú nevyhnutné pre základné fungovanie webu a nemožno ich deaktivovať.', 'functional' => 'Tieto cookies umožňujú pokročilé funkcie a personalizáciu.', 'analytics' => 'Tieto cookies nám pomáhajú pochopiť a zlepšiť využitie nášho webu.', 'marketing' => 'Tieto cookies slúžia na reklamné účely a sledovanie návštevníkov na weboch.'],
            'hu' => ['essential' => 'Ezek a sütik a weboldal alapvető működéséhez szükségesek és nem tilthatók le.', 'functional' => 'Ezek a sütik fejlett funkciókat és személyre szabást tesznek lehetővé.', 'analytics' => 'Ezek a sütik segítenek megérteni és javítani weboldalunk használatát.', 'marketing' => 'Ezek a sütik hirdetési és felhasználókövetési célokat szolgálnak.'],
            'ro' => ['essential' => 'Aceste cookie-uri sunt necesare pentru funcționalitatea de bază a site-ului și nu pot fi dezactivate.', 'functional' => 'Aceste cookie-uri permit funcționalități îmbunătățite și personalizare.', 'analytics' => 'Aceste cookie-uri ne ajută să înțelegem și să îmbunătățim utilizarea site-ului nostru.', 'marketing' => 'Aceste cookie-uri sunt utilizate în scopuri publicitare și pentru a urmări vizitatorii pe site-uri.'],
            'el' => ['essential' => 'Αυτά τα cookies είναι απαραίτητα για τη βασική λειτουργία του ιστοτόπου και δεν μπορούν να απενεργοποιηθούν.', 'functional' => 'Αυτά τα cookies επιτρέπουν βελτιωμένη λειτουργικότητα και εξατομίκευση.', 'analytics' => 'Αυτά τα cookies μας βοηθούν να κατανοήσουμε και να βελτιώσουμε τη χρήση του ιστοτόπου μας.', 'marketing' => 'Αυτά τα cookies χρησιμοποιούνται για διαφημιστικούς σκοπούς και για την παρακολούθηση επισκεπτών.'],
            'hr' => ['essential' => 'Ovi kolačići su neophodni za osnovnu funkcionalnost web stranice i ne mogu se deaktivirati.', 'functional' => 'Ovi kolačići omogućuju napredne funkcije i personalizaciju.', 'analytics' => 'Ovi kolačići pomažu nam razumjeti i poboljšati korištenje naše web stranice.', 'marketing' => 'Ovi kolačići koriste se u reklamne svrhe i za praćenje posjetitelja na web stranicama.'],
            'bg' => ['essential' => 'Тези бисквитки са необходими за основната функционалност на уебсайта и не могат да бъдат деактивирани.', 'functional' => 'Тези бисквитки позволяват разширена функционалност и персонализация.', 'analytics' => 'Тези бисквитки ни помагат да разберем и подобрим използването на нашия уебсайт.', 'marketing' => 'Тези бисквитки се използват за рекламни цели и за проследяване на посетители в уебсайтове.'],
            'sl' => ['essential' => 'Ti piškotki so nujni za osnovno delovanje spletnega mesta in jih ni mogoče onemogočiti.', 'functional' => 'Ti piškotki omogočajo napredne funkcije in personalizacijo.', 'analytics' => 'Ti piškotki nam pomagajo razumeti in izboljšati uporabo našega spletnega mesta.', 'marketing' => 'Ti piškotki se uporabljajo za oglaševalske namene in sledenje obiskovalcem na spletnih mestih.'],
            'et' => ['essential' => 'Need küpsised on vajalikud veebisaidi põhifunktsioonide jaoks ja neid ei saa keelata.', 'functional' => 'Need küpsised võimaldavad täiustatud funktsioone ja isikupärastamist.', 'analytics' => 'Need küpsised aitavad meil mõista ja parandada meie veebisaidi kasutust.', 'marketing' => 'Neid küpsiseid kasutatakse reklaamimiseks ja külastajate jälgimiseks veebisaitidel.'],
            'lv' => ['essential' => 'Šīs sīkdatnes ir nepieciešamas tīmekļa vietnes pamata funkcionalitātei un tās nevar atspējot.', 'functional' => 'Šīs sīkdatnes nodrošina uzlabotu funkcionalitāti un personalizāciju.', 'analytics' => 'Šīs sīkdatnes palīdz mums izprast un uzlabot mūsu tīmekļa vietnes izmantošanu.', 'marketing' => 'Šīs sīkdatnes tiek izmantotas reklāmas nolūkiem un apmeklētāju izsekošanai tīmekļa vietnēs.'],
            'lt' => ['essential' => 'Šie slapukai yra būtini pagrindiniam svetainės veikimui ir negali būti išjungti.', 'functional' => 'Šie slapukai leidžia naudoti pažangias funkcijas ir personalizavimą.', 'analytics' => 'Šie slapukai padeda mums suprasti ir pagerinti mūsų svetainės naudojimą.', 'marketing' => 'Šie slapukai naudojami reklamos tikslais ir lankytojų sekimui svetainėse.'],
            'ja' => ['essential' => 'これらのCookieはウェブサイトの基本機能に必要であり、無効にすることはできません。', 'functional' => 'これらのCookieは拡張機能とパーソナライゼーションを可能にします。', 'analytics' => 'これらのCookieはウェブサイトの利用状況を理解し改善するのに役立ちます。', 'marketing' => 'これらのCookieは広告目的およびウェブサイト間での訪問者の追跡に使用されます。'],
            'ko' => ['essential' => '이 쿠키는 웹사이트의 기본 기능에 필요하며 비활성화할 수 없습니다.', 'functional' => '이 쿠키는 향상된 기능과 개인화를 가능하게 합니다.', 'analytics' => '이 쿠키는 웹사이트 사용을 이해하고 개선하는 데 도움이 됩니다.', 'marketing' => '이 쿠키는 광고 및 웹사이트 간 방문자 추적에 사용됩니다.'],
            'zh' => ['essential' => '这些 Cookie 是网站基本功能所必需的，无法禁用。', 'functional' => '这些 Cookie 支持增强功能和个性化设置。', 'analytics' => '这些 Cookie 帮助我们了解和改进网站的使用情况。', 'marketing' => '这些 Cookie 用于广告目的和跨网站跟踪访问者。'],
            'ar' => ['essential' => 'ملفات تعريف الارتباط هذه ضرورية لوظائف الموقع الأساسية ولا يمكن تعطيلها.', 'functional' => 'ملفات تعريف الارتباط هذه تتيح وظائف متقدمة وتخصيصاً.', 'analytics' => 'ملفات تعريف الارتباط هذه تساعدنا على فهم وتحسين استخدام موقعنا.', 'marketing' => 'تُستخدم ملفات تعريف الارتباط هذه لأغراض الإعلان وتتبع الزوار عبر المواقع.'],
            'he' => ['essential' => 'עוגיות אלו נדרשות לפונקציונליות בסיסית של האתר ולא ניתן להשביתן.', 'functional' => 'עוגיות אלו מאפשרות פונקציונליות משופרת והתאמה אישית.', 'analytics' => 'עוגיות אלו עוזרות לנו להבין ולשפר את השימוש באתר שלנו.', 'marketing' => 'עוגיות אלו משמשות למטרות פרסום ומעקב אחר מבקרים באתרים.'],
            'hi' => ['essential' => 'ये कुकीज़ वेबसाइट की बुनियादी कार्यक्षमता के लिए आवश्यक हैं और इन्हें अक्षम नहीं किया जा सकता।', 'functional' => 'ये कुकीज़ उन्नत कार्यक्षमता और वैयक्तिकरण को सक्षम करती हैं।', 'analytics' => 'ये कुकीज़ हमें हमारी वेबसाइट के उपयोग को समझने और सुधारने में मदद करती हैं।', 'marketing' => 'इन कुकीज़ का उपयोग विज्ञापन और वेबसाइटों पर आगंतुकों को ट्रैक करने के लिए किया जाता है।'],
            'th' => ['essential' => 'คุกกี้เหล่านี้จำเป็นสำหรับการทำงานพื้นฐานของเว็บไซต์และไม่สามารถปิดใช้งานได้', 'functional' => 'คุกกี้เหล่านี้ช่วยเพิ่มฟังก์ชันการทำงานและการปรับแต่งส่วนบุคคล', 'analytics' => 'คุกกี้เหล่านี้ช่วยให้เราเข้าใจและปรับปรุงการใช้งานเว็บไซต์ของเรา', 'marketing' => 'คุกกี้เหล่านี้ใช้เพื่อวัตถุประสงค์ในการโฆษณาและติดตามผู้เยี่ยมชมข้ามเว็บไซต์'],
            'vi' => ['essential' => 'Những cookie này cần thiết cho chức năng cơ bản của trang web và không thể tắt.', 'functional' => 'Những cookie này cho phép chức năng nâng cao và cá nhân hóa.', 'analytics' => 'Những cookie này giúp chúng tôi hiểu và cải thiện cách sử dụng trang web.', 'marketing' => 'Những cookie này được sử dụng cho mục đích quảng cáo và theo dõi khách truy cập trên các trang web.'],
            'id' => ['essential' => 'Cookie ini diperlukan untuk fungsionalitas dasar situs web dan tidak dapat dinonaktifkan.', 'functional' => 'Cookie ini memungkinkan fungsionalitas yang ditingkatkan dan personalisasi.', 'analytics' => 'Cookie ini membantu kami memahami dan meningkatkan penggunaan situs web kami.', 'marketing' => 'Cookie ini digunakan untuk tujuan periklanan dan melacak pengunjung di situs web.'],
            'ms' => ['essential' => 'Kuki ini diperlukan untuk fungsi asas laman web dan tidak boleh dilumpuhkan.', 'functional' => 'Kuki ini membolehkan fungsi yang dipertingkatkan dan pemperibadian.', 'analytics' => 'Kuki ini membantu kami memahami dan meningkatkan penggunaan laman web kami.', 'marketing' => 'Kuki ini digunakan untuk tujuan pengiklanan dan menjejaki pelawat merentasi laman web.'],
            'tr' => ['essential' => 'Bu çerezler, web sitesinin temel işlevselliği için gereklidir ve devre dışı bırakılamaz.', 'functional' => 'Bu çerezler gelişmiş işlevsellik ve kişiselleştirme sağlar.', 'analytics' => 'Bu çerezler, web sitemizin kullanımını anlamamıza ve iyileştirmemize yardımcı olur.', 'marketing' => 'Bu çerezler, reklamcılık ve web sitelerinde ziyaretçileri takip etmek amacıyla kullanılır.'],
            'uk' => ['essential' => 'Ці cookie необхідні для базової функціональності веб-сайту і не можуть бути вимкнені.', 'functional' => 'Ці cookie забезпечують розширену функціональність та персоналізацію.', 'analytics' => 'Ці cookie допомагають нам зрозуміти та покращити використання нашого веб-сайту.', 'marketing' => 'Ці cookie використовуються для рекламних цілей та відстеження відвідувачів на веб-сайтах.'],
            'sr' => ['essential' => 'Ovi kolačići su neophodni za osnovnu funkcionalnost veb sajta i ne mogu se deaktivirati.', 'functional' => 'Ovi kolačići omogućavaju napredne funkcije i personalizaciju.', 'analytics' => 'Ovi kolačići pomažu nam da razumemo i poboljšamo korišćenje našeg veb sajta.', 'marketing' => 'Ovi kolačići se koriste u reklamne svrhe i za praćenje posetilaca na veb sajtovima.'],
            'ka' => ['essential' => 'ეს ქუქები აუცილებელია ვებსაიტის ძირითადი ფუნქციონირებისთვის და მათი გამორთვა შეუძლებელია.', 'functional' => 'ეს ქუქები უზრუნველყოფენ გაფართოებულ ფუნქციონალობას და პერსონალიზაციას.', 'analytics' => 'ეს ქუქები გვეხმარება ჩვენი ვებსაიტის გამოყენების გაგებასა და გაუმჯობესებაში.', 'marketing' => 'ეს ქუქები გამოიყენება სარეკლამო მიზნებისთვის და ვიზიტორთა თვალყურის დევნისთვის.'],
            'sw' => ['essential' => 'Kuki hizi zinahitajika kwa utendaji wa msingi wa tovuti na haziwezi kuzimwa.', 'functional' => 'Kuki hizi zinawezesha utendaji ulioboreshwa na ubinafsishaji.', 'analytics' => 'Kuki hizi zinatusaidia kuelewa na kuboresha matumizi ya tovuti yetu.', 'marketing' => 'Kuki hizi zinatumika kwa madhumuni ya matangazo na kufuatilia wageni kwenye tovuti.'],
            'ga' => ['essential' => 'Tá na fianáin seo riachtanach le haghaidh feidhmiúlacht bhunúsach an tsuímh ghréasáin agus ní féidir iad a dhíchumasú.', 'functional' => 'Cuireann na fianáin seo feidhmiúlacht fheabhsaithe agus pearsanú ar fáil.', 'analytics' => 'Cabhraíonn na fianáin seo linn úsáid ár suímh ghréasáin a thuiscint agus a fheabhsú.', 'marketing' => 'Úsáidtear na fianáin seo chun críocha fógraíochta agus chun cuairteoirí a rianú ar fud suíomhanna gréasáin.'],
            'ru' => ['essential' => 'Эти cookie необходимы для базовой функциональности сайта и не могут быть отключены.', 'functional' => 'Эти cookie обеспечивают расширенную функциональность и персонализацию.', 'analytics' => 'Эти cookie помогают нам понять и улучшить использование нашего сайта.', 'marketing' => 'Эти cookie используются для рекламных целей и отслеживания посетителей на сайтах.'],
            'bs' => ['essential' => 'Ovi kolačići su neophodni za osnovnu funkcionalnost web stranice i ne mogu se deaktivirati.', 'functional' => 'Ovi kolačići omogućavaju napredne funkcije i personalizaciju.', 'analytics' => 'Ovi kolačići pomažu nam razumjeti i poboljšati korištenje naše web stranice.', 'marketing' => 'Ovi kolačići se koriste u reklamne svrhe i za praćenje posjetilaca na web stranicama.'],
            'ca' => ['essential' => 'Aquestes galetes són necessàries per a la funcionalitat bàsica del lloc web i no es poden desactivar.', 'functional' => 'Aquestes galetes permeten funcionalitats avançades i personalització.', 'analytics' => 'Aquestes galetes ens ajuden a entendre i millorar l\'ús del nostre lloc web.', 'marketing' => 'Aquestes galetes s\'utilitzen amb finalitats publicitàries i per fer seguiment dels visitants als llocs web.'],
            'eu' => ['essential' => 'Cookie hauek webgunearen oinarrizko funtzionamenduarako beharrezkoak dira eta ezin dira desgaitu.', 'functional' => 'Cookie hauek funtzionalitate aurreratua eta pertsonalizazioa ahalbidetzen dute.', 'analytics' => 'Cookie hauek gure webgunearen erabilera ulertu eta hobetzen laguntzen digute.', 'marketing' => 'Cookie hauek publizitate helburuetarako eta bisitariak webguneetan jarraitzeko erabiltzen dira.'],
            'gl' => ['essential' => 'Estas cookies son necesarias para a funcionalidade básica do sitio web e non se poden desactivar.', 'functional' => 'Estas cookies permiten funcionalidades avanzadas e personalización.', 'analytics' => 'Estas cookies axúdannos a comprender e mellorar o uso do noso sitio web.', 'marketing' => 'Estas cookies utilízanse con fins publicitarios e para rastrexar visitantes nos sitios web.'],
            'mr' => ['essential' => 'या कुकीज वेबसाइटच्या मूलभूत कार्यक्षमतेसाठी आवश्यक आहेत आणि त्या अक्षम केल्या जाऊ शकत नाहीत.', 'functional' => 'या कुकीज प्रगत कार्यक्षमता आणि वैयक्तिकरण सक्षम करतात.', 'analytics' => 'या कुकीज आम्हाला आमच्या वेबसाइटचा वापर समजून घेण्यास आणि सुधारण्यास मदत करतात.', 'marketing' => 'या कुकीज जाहिरात उद्देशांसाठी आणि वेबसाइटवरील अभ्यागतांचा मागोवा घेण्यासाठी वापरल्या जातात.'],
        ];

        $lang_descs = $descriptions[$lang] ?? $descriptions['en'];
        return $lang_descs[$category] ?? '';
    }

    /**
     * Get data export labels
     */
    private function get_data_export_labels($lang)
    {
        $lang = Biscotti_Languages::to_legacy($lang);
        $labels = [
            'de' => ['title' => 'Ihre Daten exportieren', 'description' => 'Laden Sie eine Kopie Ihrer bei uns gespeicherten Daten herunter (Art. 15 DSGVO).', 'download' => 'Daten herunterladen'],
            'en' => ['title' => 'Export Your Data', 'description' => 'Download a copy of your data stored with us (GDPR Art. 15).', 'download' => 'Download Data'],
            'fr' => ['title' => 'Exporter vos données', 'description' => 'Téléchargez une copie de vos données stockées chez nous (Art. 15 RGPD).', 'download' => 'Télécharger les données'],
            'es' => ['title' => 'Exportar sus datos', 'description' => 'Descargue una copia de sus datos almacenados con nosotros (Art. 15 RGPD).', 'download' => 'Descargar datos'],
            'it' => ['title' => 'Esporta i tuoi dati', 'description' => 'Scarica una copia dei tuoi dati memorizzati presso di noi (Art. 15 GDPR).', 'download' => 'Scarica dati'],
            'nl' => ['title' => 'Uw gegevens exporteren', 'description' => 'Download een kopie van uw bij ons opgeslagen gegevens (Art. 15 AVG).', 'download' => 'Gegevens downloaden'],
            'pl' => ['title' => 'Eksportuj swoje dane', 'description' => 'Pobierz kopię swoich danych przechowywanych u nas (Art. 15 RODO).', 'download' => 'Pobierz dane'],
            'pt' => ['title' => 'Exportar os seus dados', 'description' => 'Descarregue uma cópia dos seus dados armazenados connosco (Art. 15 RGPD).', 'download' => 'Descarregar dados'],
            'da' => ['title' => 'Eksporter dine data', 'description' => 'Download en kopi af dine data, der er gemt hos os (Art. 15 GDPR).', 'download' => 'Download data'],
            'sv' => ['title' => 'Exportera dina data', 'description' => 'Ladda ner en kopia av dina uppgifter som lagras hos oss (Art. 15 GDPR).', 'download' => 'Ladda ner data'],
            'fi' => ['title' => 'Vie tietosi', 'description' => 'Lataa kopio meillä tallennetuista tiedoistasi (GDPR Art. 15).', 'download' => 'Lataa tiedot'],
            'no' => ['title' => 'Eksporter dataene dine', 'description' => 'Last ned en kopi av dataene dine som er lagret hos oss (Art. 15 GDPR).', 'download' => 'Last ned data'],
            'cs' => ['title' => 'Exportovat vaše data', 'description' => 'Stáhněte si kopii vašich dat uložených u nás (čl. 15 GDPR).', 'download' => 'Stáhnout data'],
            'sk' => ['title' => 'Exportovať vaše údaje', 'description' => 'Stiahnite si kópiu vašich údajov uložených u nás (čl. 15 GDPR).', 'download' => 'Stiahnuť údaje'],
            'hu' => ['title' => 'Adatai exportálása', 'description' => 'Töltse le a nálunk tárolt adatai másolatát (GDPR 15. cikk).', 'download' => 'Adatok letöltése'],
            'ro' => ['title' => 'Exportați datele dvs.', 'description' => 'Descărcați o copie a datelor dvs. stocate la noi (Art. 15 GDPR).', 'download' => 'Descărcați datele'],
            'el' => ['title' => 'Εξαγωγή των δεδομένων σας', 'description' => 'Κατεβάστε ένα αντίγραφο των δεδομένων σας που αποθηκεύονται σε εμάς (Άρθρο 15 GDPR).', 'download' => 'Λήψη δεδομένων'],
            'hr' => ['title' => 'Izvezite svoje podatke', 'description' => 'Preuzmite kopiju svojih podataka pohranjenih kod nas (čl. 15 GDPR).', 'download' => 'Preuzmi podatke'],
            'bg' => ['title' => 'Експортиране на данните ви', 'description' => 'Изтеглете копие на данните си, съхранявани при нас (чл. 15 GDPR).', 'download' => 'Изтегляне на данни'],
            'sl' => ['title' => 'Izvozite svoje podatke', 'description' => 'Prenesite kopijo svojih podatkov, shranjenih pri nas (čl. 15 GDPR).', 'download' => 'Prenesi podatke'],
            'et' => ['title' => 'Ekspordi oma andmed', 'description' => 'Laadige alla koopia oma andmetest, mis on meil salvestatud (GDPR art. 15).', 'download' => 'Laadi andmed alla'],
            'lv' => ['title' => 'Eksportēt savus datus', 'description' => 'Lejupielādējiet savu datu kopiju, kas tiek glabāti pie mums (VDAR 15. pants).', 'download' => 'Lejupielādēt datus'],
            'lt' => ['title' => 'Eksportuoti savo duomenis', 'description' => 'Atsisiųskite savo duomenų, saugomų pas mus, kopiją (BDAR 15 str.).', 'download' => 'Atsisiųsti duomenis'],
            'ja' => ['title' => 'データのエクスポート', 'description' => '当社に保存されているデータのコピーをダウンロードできます（GDPR第15条）。', 'download' => 'データをダウンロード'],
            'ko' => ['title' => '데이터 내보내기', 'description' => '당사에 저장된 데이터 사본을 다운로드하세요 (GDPR 제15조).', 'download' => '데이터 다운로드'],
            'zh' => ['title' => '导出您的数据', 'description' => '下载我们存储的您的数据副本（GDPR 第15条）。', 'download' => '下载数据'],
            'ar' => ['title' => 'تصدير بياناتك', 'description' => 'قم بتنزيل نسخة من بياناتك المخزنة لدينا (المادة 15 من اللائحة العامة لحماية البيانات).', 'download' => 'تنزيل البيانات'],
            'he' => ['title' => 'ייצוא הנתונים שלך', 'description' => 'הורד עותק של הנתונים שלך המאוחסנים אצלנו (סעיף 15 GDPR).', 'download' => 'הורד נתונים'],
            'hi' => ['title' => 'अपना डेटा निर्यात करें', 'description' => 'हमारे पास संग्रहीत आपके डेटा की एक प्रति डाउनलोड करें (GDPR अनुच्छेद 15)।', 'download' => 'डेटा डाउनलोड करें'],
            'th' => ['title' => 'ส่งออกข้อมูลของคุณ', 'description' => 'ดาวน์โหลดสำเนาข้อมูลของคุณที่จัดเก็บไว้กับเรา (GDPR มาตรา 15)', 'download' => 'ดาวน์โหลดข้อมูล'],
            'vi' => ['title' => 'Xuất dữ liệu của bạn', 'description' => 'Tải xuống bản sao dữ liệu của bạn được lưu trữ tại chúng tôi (GDPR Điều 15).', 'download' => 'Tải dữ liệu'],
            'id' => ['title' => 'Ekspor data Anda', 'description' => 'Unduh salinan data Anda yang tersimpan di kami (GDPR Pasal 15).', 'download' => 'Unduh data'],
            'ms' => ['title' => 'Eksport data anda', 'description' => 'Muat turun salinan data anda yang disimpan bersama kami (GDPR Perkara 15).', 'download' => 'Muat turun data'],
            'tr' => ['title' => 'Verilerinizi dışa aktarın', 'description' => 'Bizde saklanan verilerinizin bir kopyasını indirin (GDPR Madde 15).', 'download' => 'Verileri indir'],
            'uk' => ['title' => 'Експорт ваших даних', 'description' => 'Завантажте копію ваших даних, збережених у нас (GDPR ст. 15).', 'download' => 'Завантажити дані'],
            'sr' => ['title' => 'Izvezite svoje podatke', 'description' => 'Preuzmite kopiju svojih podataka koji se čuvaju kod nas (GDPR čl. 15).', 'download' => 'Preuzmi podatke'],
            'ka' => ['title' => 'თქვენი მონაცემების ექსპორტი', 'description' => 'ჩამოტვირთეთ ჩვენთან შენახული თქვენი მონაცემების ასლი (GDPR მუხლი 15).', 'download' => 'მონაცემების ჩამოტვირთვა'],
            'sw' => ['title' => 'Hamisha data yako', 'description' => 'Pakua nakala ya data yako iliyohifadhiwa kwetu (GDPR Kifungu 15).', 'download' => 'Pakua data'],
            'ga' => ['title' => 'Easpórtáil do shonraí', 'description' => 'Íoslódáil cóip de do shonraí atá stóráilte againn (GDPR Airteagal 15).', 'download' => 'Íoslódáil sonraí'],
            'ru' => ['title' => 'Экспорт ваших данных', 'description' => 'Скачайте копию ваших данных, хранящихся у нас (GDPR ст. 15).', 'download' => 'Скачать данные'],
            'bs' => ['title' => 'Izvezite svoje podatke', 'description' => 'Preuzmite kopiju svojih podataka pohranjenih kod nas (GDPR čl. 15).', 'download' => 'Preuzmi podatke'],
            'ca' => ['title' => 'Exporteu les vostres dades', 'description' => 'Descarregueu una còpia de les vostres dades emmagatzemades (RGPD Art. 15).', 'download' => 'Descarregar dades'],
            'eu' => ['title' => 'Esportatu zure datuak', 'description' => 'Deskargatu gure zerbitzarian gordetako zure datuen kopia (GDPR 15. art.).', 'download' => 'Datuak deskargatu'],
            'gl' => ['title' => 'Exportar os seus datos', 'description' => 'Descargue unha copia dos seus datos almacenados connosco (RXPD Art. 15).', 'download' => 'Descargar datos'],
            'mr' => ['title' => 'आपला डेटा निर्यात करा', 'description' => 'आमच्याकडे संग्रहित आपल्या डेटाची प्रत डाउनलोड करा (GDPR कलम 15).', 'download' => 'डेटा डाउनलोड करा'],
        ];

        return $labels[$lang] ?? $labels['en'];
    }

    /**
     * Get CCPA labels
     */
    private function get_ccpa_labels($lang)
    {
        $lang = Biscotti_Languages::to_legacy($lang);
        $labels = [
            'de' => ['doNotSell' => 'Meine Daten nicht verkaufen', 'doNotSellDesc' => 'Sie haben das Recht zu verlangen, dass Ihre persönlichen Daten nicht verkauft werden.'],
            'en' => ['doNotSell' => 'Do Not Sell My Data', 'doNotSellDesc' => 'You have the right to request that your personal data not be sold.'],
            'fr' => ['doNotSell' => 'Ne pas vendre mes données', 'doNotSellDesc' => 'Vous avez le droit de demander que vos données personnelles ne soient pas vendues.'],
            'es' => ['doNotSell' => 'No vender mis datos', 'doNotSellDesc' => 'Tiene derecho a solicitar que sus datos personales no sean vendidos.'],
            'it' => ['doNotSell' => 'Non vendere i miei dati', 'doNotSellDesc' => 'Hai il diritto di richiedere che i tuoi dati personali non vengano venduti.'],
            'nl' => ['doNotSell' => 'Verkoop mijn gegevens niet', 'doNotSellDesc' => 'U heeft het recht te verzoeken dat uw persoonlijke gegevens niet worden verkocht.'],
            'pl' => ['doNotSell' => 'Nie sprzedawaj moich danych', 'doNotSellDesc' => 'Masz prawo zażądać, aby Twoje dane osobowe nie były sprzedawane.'],
            'pt' => ['doNotSell' => 'Não vender os meus dados', 'doNotSellDesc' => 'Tem o direito de solicitar que os seus dados pessoais não sejam vendidos.'],
            'da' => ['doNotSell' => 'Sælg ikke mine data', 'doNotSellDesc' => 'Du har ret til at anmode om, at dine personlige data ikke sælges.'],
            'sv' => ['doNotSell' => 'Sälj inte mina data', 'doNotSellDesc' => 'Du har rätt att begära att dina personuppgifter inte säljs.'],
            'fi' => ['doNotSell' => 'Älä myy tietojani', 'doNotSellDesc' => 'Sinulla on oikeus pyytää, ettei henkilötietojasi myydä.'],
            'no' => ['doNotSell' => 'Ikke selg mine data', 'doNotSellDesc' => 'Du har rett til å be om at dine personopplysninger ikke selges.'],
            'cs' => ['doNotSell' => 'Neprodávejte moje data', 'doNotSellDesc' => 'Máte právo požadovat, aby vaše osobní údaje nebyly prodávány.'],
            'sk' => ['doNotSell' => 'Nepredávajte moje údaje', 'doNotSellDesc' => 'Máte právo požadovať, aby vaše osobné údaje neboli predávané.'],
            'hu' => ['doNotSell' => 'Ne adja el az adataimat', 'doNotSellDesc' => 'Ön jogosult kérni, hogy személyes adatait ne értékesítsék.'],
            'ro' => ['doNotSell' => 'Nu vindeți datele mele', 'doNotSellDesc' => 'Aveți dreptul de a solicita ca datele dvs. personale să nu fie vândute.'],
            'el' => ['doNotSell' => 'Μην πουλάτε τα δεδομένα μου', 'doNotSellDesc' => 'Έχετε το δικαίωμα να ζητήσετε να μην πωλούνται τα προσωπικά σας δεδομένα.'],
            'hr' => ['doNotSell' => 'Ne prodajite moje podatke', 'doNotSellDesc' => 'Imate pravo zatražiti da se vaši osobni podaci ne prodaju.'],
            'bg' => ['doNotSell' => 'Не продавайте данните ми', 'doNotSellDesc' => 'Имате право да поискате вашите лични данни да не бъдат продавани.'],
            'sl' => ['doNotSell' => 'Ne prodajajte mojih podatkov', 'doNotSellDesc' => 'Imate pravico zahtevati, da se vaši osebni podatki ne prodajajo.'],
            'et' => ['doNotSell' => 'Ärge müüge minu andmeid', 'doNotSellDesc' => 'Teil on õigus nõuda, et teie isikuandmeid ei müüdaks.'],
            'lv' => ['doNotSell' => 'Nepārdodiet manus datus', 'doNotSellDesc' => 'Jums ir tiesības pieprasīt, lai jūsu personas dati netiktu pārdoti.'],
            'lt' => ['doNotSell' => 'Neparduokite mano duomenų', 'doNotSellDesc' => 'Turite teisę reikalauti, kad jūsų asmens duomenys nebūtų parduodami.'],
            'ja' => ['doNotSell' => '私のデータを販売しないでください', 'doNotSellDesc' => 'お客様は個人データの販売停止を要求する権利があります。'],
            'ko' => ['doNotSell' => '내 데이터를 판매하지 마세요', 'doNotSellDesc' => '귀하는 개인 데이터가 판매되지 않도록 요청할 권리가 있습니다.'],
            'zh' => ['doNotSell' => '不要出售我的数据', 'doNotSellDesc' => '您有权要求不出售您的个人数据。'],
            'ar' => ['doNotSell' => 'لا تبيعوا بياناتي', 'doNotSellDesc' => 'لديك الحق في طلب عدم بيع بياناتك الشخصية.'],
            'he' => ['doNotSell' => 'אל תמכרו את הנתונים שלי', 'doNotSellDesc' => 'יש לך הזכות לבקש שהנתונים האישיים שלך לא יימכרו.'],
            'hi' => ['doNotSell' => 'मेरा डेटा न बेचें', 'doNotSellDesc' => 'आपको यह अनुरोध करने का अधिकार है कि आपका व्यक्तिगत डेटा न बेचा जाए।'],
            'th' => ['doNotSell' => 'อย่าขายข้อมูลของฉัน', 'doNotSellDesc' => 'คุณมีสิทธิ์ขอให้ไม่ขายข้อมูลส่วนบุคคลของคุณ'],
            'vi' => ['doNotSell' => 'Không bán dữ liệu của tôi', 'doNotSellDesc' => 'Bạn có quyền yêu cầu không bán dữ liệu cá nhân của mình.'],
            'id' => ['doNotSell' => 'Jangan jual data saya', 'doNotSellDesc' => 'Anda berhak meminta agar data pribadi Anda tidak dijual.'],
            'ms' => ['doNotSell' => 'Jangan jual data saya', 'doNotSellDesc' => 'Anda berhak untuk meminta data peribadi anda tidak dijual.'],
            'tr' => ['doNotSell' => 'Verilerimi satmayın', 'doNotSellDesc' => 'Kişisel verilerinizin satılmamasını talep etme hakkınız vardır.'],
            'uk' => ['doNotSell' => 'Не продавайте мої дані', 'doNotSellDesc' => 'Ви маєте право вимагати, щоб ваші персональні дані не продавалися.'],
            'sr' => ['doNotSell' => 'Ne prodajte moje podatke', 'doNotSellDesc' => 'Imate pravo da zahtevate da se vaši lični podaci ne prodaju.'],
            'ka' => ['doNotSell' => 'არ გაყიდოთ ჩემი მონაცემები', 'doNotSellDesc' => 'თქვენ გაქვთ უფლება მოითხოვოთ, რომ თქვენი პერსონალური მონაცემები არ გაიყიდოს.'],
            'sw' => ['doNotSell' => 'Usiuze data yangu', 'doNotSellDesc' => 'Una haki ya kuomba data yako ya kibinafsi isiuzwe.'],
            'ga' => ['doNotSell' => 'Ná díol mo shonraí', 'doNotSellDesc' => 'Tá sé de cheart agat iarraidh nach ndíolfar do shonraí pearsanta.'],
            'ru' => ['doNotSell' => 'Не продавайте мои данные', 'doNotSellDesc' => 'Вы имеете право потребовать, чтобы ваши персональные данные не продавались.'],
            'bs' => ['doNotSell' => 'Ne prodajte moje podatke', 'doNotSellDesc' => 'Imate pravo zahtijevati da se vaši lični podaci ne prodaju.'],
            'ca' => ['doNotSell' => 'No vengueu les meves dades', 'doNotSellDesc' => 'Teniu dret a sol·licitar que les vostres dades personals no es venguin.'],
            'eu' => ['doNotSell' => 'Ez saldu nire datuak', 'doNotSellDesc' => 'Zure datu pertsonalak ez saltzeko eskatzeko eskubidea duzu.'],
            'gl' => ['doNotSell' => 'Non venda os meus datos', 'doNotSellDesc' => 'Ten dereito a solicitar que os seus datos persoais non sexan vendidos.'],
            'mr' => ['doNotSell' => 'माझा डेटा विकू नका', 'doNotSellDesc' => 'आपला वैयक्तिक डेटा विकला जाऊ नये अशी विनंती करण्याचा आपल्याला अधिकार आहे.'],
        ];

        return $labels[$lang] ?? $labels['en'];
    }
}

// Initialize shortcodes
Biscotti_Shortcodes::get_instance();
