<?php

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

class ASSI_Tools {

    public static function getTonality() {
        return array(
            'aggressive' => __('Aggressive', 'assistini'),
            'argumentative' => __('Argumentative', 'assistini'),
            'conversational' => __('Conversational', 'assistini'),
            'descriptive' => __('Descriptive', 'assistini'),
            'expository' => __('Expository', 'assistini'),
            'formal' => __('Formal', 'assistini'),
            'friendly' => __('Friendly', 'assistini'),
            'funny' => __('Funny', 'assistini'),
            'helpful' => __('Helpful', 'assistini'),
            'humorous' => __('Humorous', 'assistini'),
            'informal' => __('Informal', 'assistini'),
            'informative' => __('Informative', 'assistini'),
            'inspirational' => __('Inspirational', 'assistini'),
            'instructional' => __('Instructional', 'assistini'),
            'optimistic' => __('Optimistic', 'assistini'),
            'persuasive' => __('Persuasive', 'assistini'),
            'poetic' => __('Poetic', 'assistini'),
            'professional' => __('Professional', 'assistini'),
            'sarcastic' => __('Sarcastic', 'assistini'),
            'technical' => __('Technical', 'assistini'),
            'urgent' => __('Urgent', 'assistini'),
            'witty' => __('Witty', 'assistini')
        );
    }

    public static function getPointOfView() {
        return array(
            'neutral' => __('Neutral', 'assistini'),
            '1st-person' => __('1st Person (I, We)', 'assistini'),
            '2nd-person' => __('2nd Person (You, informal)', 'assistini'),
            '2nd-person-she' => __('2nd Person (You, formal)', 'assistini'),
            '3rd-person' => __('3rd Person (He, She, It, They)', 'assistini')
        );
    }

    public static function getContentLength() {
        return array(
            'short' => __('Short', 'assistini'),
            'medium' => __('Medium', 'assistini'),
            'long' => __('Long', 'assistini')
        );
    }

    public static function getSize() {
        return array(
            'auto' => __('Auto', 'assistini'),
            '1024x1024' => '1024x1024',
            '1536x1024' => '1536x1024',
            '1024x1536' => '1024x1536'
        );
    }

    public static function getQuality() {
        return array(
            'auto' => __('Auto', 'assistini'),
            'low' => __('Low', 'assistini'),
            'medium' => __('Medium', 'assistini'),
            'high' => __('High', 'assistini'),
        );
    }

    public static function getOutputFormat() {
        return array(
            'png' => __('.PNG', 'assistini'),
            'jpeg' => __('.JPEG', 'assistini'),
            'webp' => __('.WEBP', 'assistini')
        );
    }

    public static function getArtStyle() {
        return array(
            __('Traditional & Fine Art', 'assistini') => array(
                'photorealism' => __('Photorealism - life-like detail, accurate lighting/perspective', 'assistini'),
                'realism' => __('Realism - faithful representation of subjects', 'assistini'),
                'impressionism' => __('Impressionism - loose brushwork, light & color over detail', 'assistini'),
                'post-impressionism' => __('Post-Impressionism - bold color, expressive forms', 'assistini'),
                'expressionism' => __('Expressionism - emotional distortion, vivid colors', 'assistini'),
                'fauvism' => __('Fauvism - wild color, simplified forms', 'assistini'),
                'cubism' => __('Cubism - fractured geometry, multiple viewpoints', 'assistini'),
                'surrealism' => __('Surrealism - dreamlike, uncanny juxtapositions', 'assistini'),
                'abstract' => __('Abstract - non-representational shapes and color fields', 'assistini'),
                'minimalism' => __('Minimalism - extreme reduction, strong negative space', 'assistini'),
                'art-deco' => __('Art Deco - luxe symmetry, metallics, stepped forms', 'assistini'),
                'art-nouveau' => __('Art Nouveau - ornate curves, floral motifs', 'assistini'),
                'baroque' => __('Baroque - dramatic light, dynamic composition', 'assistini'),
                'rococo' => __('Rococo - ornate, playful, pastel elegance', 'assistini'),
                'neoclassicism' => __('Neoclassicism - classical restraint, clear lines', 'assistini'),
                'romanticism' => __('Romanticism - sublime nature, heightened emotion', 'assistini'),
                'renaissance' => __('Renaissance - balanced composition, realistic anatomy', 'assistini'),
                'pointillism' => __('Pointillism - dots of color blend optically', 'assistini'),
                'ink-wash' => __('Ink Wash / Sumi-e - monochrome brushwork, tonal washes', 'assistini'),
                'line-art' => __('Line Art - contour-focused, minimal shading', 'assistini'),
                'woodcut' => __('Woodcut / Linocut - bold, high-contrast carving marks', 'assistini'),
                'watercolor' => __('Watercolor - translucent washes, soft edges', 'assistini'),
                'gouache' => __('Gouache - matte, opaque watercolor look', 'assistini'),
                'oil-painting' => __('Oil Painting - rich blending, textured impasto', 'assistini'),
                'pastel' => __('Pastel - soft, chalky texture', 'assistini'),
            ),
            __('Illustration, Comics & Pop', 'assistini') => array(
                'cartoon' => __('Cartoon - simplified forms, exaggerated features', 'assistini'),
                'anime' => __('Anime / Manga - stylized characters, cel-style shading', 'assistini'),
                'comic-book' => __('Comic Book - inked lines, halftones, dynamic panels', 'assistini'),
                'pop-art' => __('Pop Art - bold flats, commercial culture motifs', 'assistini'),
                'childrens-book' => __('Children\'s Book - friendly palettes, soft shapes', 'assistini'),
                'flat-vector' => __('Flat / Vector - clean shapes, solid fills, minimal shading', 'assistini'),
                'collage' => __('Cut-Paper / Collage - layered textures, visible edges', 'assistini'),
            ),
            __('Photography-Driven Looks', 'assistini') => array(
                'cinematic' => __('Cinematic - filmic framing, depth of field, grading', 'assistini'),
                'noir' => __('Noir - stark shadows, high contrast, moody lighting', 'assistini'),
                'hdr' => __('HDR - expanded dynamic range, crisp detail', 'assistini'),
                'monochrome' => __('Monochrome - black-and-white tonal focus', 'assistini'),
                'vintage' => __('Vintage / Retro - faded film, grain, light leaks', 'assistini'),
                'pictorialism' => __('Pictorialism - soft focus, painterly tonality', 'assistini'),
            ),
            __('Digital, 3D & Contemporary', 'assistini') => array(
                'digital-painting' => __('Digital Painting - painterly brushes, clean finish', 'assistini'),
                'matte-painting' => __('Matte Painting - epic environments, photobashing', 'assistini'),
                'low-poly' => __('Low-Poly - faceted geometry, simplified forms', 'assistini'),
                'voxel' => __('Voxel - blocky, pixel-3D aesthetic', 'assistini'),
                'isometric' => __('Isometric - axonometric angle, game-map vibe', 'assistini'),
                'photobashing' => __('Photobashing - photo composites + paintover', 'assistini'),
                'kitbash' => __('Kitbash / Hard-Surface - detailed mechanical forms', 'assistini'),
                'pbr-realism' => __('PBR Realism - physically-based materials & light', 'assistini'),
                'ray-traced' => __('Ray-Traced / Path-Traced - accurate reflections/caustics', 'assistini'),
                'cel-shading' => __('Toon / Cel Shading - flat tones, crisp outlines', 'assistini'),
                'vaporwave' => __('Neon / Vaporwave - retro-futurist synth palette', 'assistini'),
                'glitch' => __('Glitch / Datamosh - digital errors as texture', 'assistini'),
                'cyberpunk' => __('Cyberpunk - neon-noir, dense tech urbanism', 'assistini'),
                'solarpunk' => __('Solarpunk - bright eco-futures, biophilic design', 'assistini'),
                'steampunk' => __('Steampunk - retro-tech, brass & rivets', 'assistini'),
                'dieselpunk' => __('Dieselpunk - interwar grit, engines & steel', 'assistini'),
                'biomorphic' => __('Biomorphic / Organic - flowing, nature-inspired forms', 'assistini'),
                'generative' => __('Generative / Algorithmic - procedural, code-driven patterns', 'assistini'),
            ),
            __('Genre & Thematic', 'assistini') => array(
                'fantasy-art' => __('Fantasy Art - mythical creatures, epic vistas', 'assistini'),
                'sci-fi' => __('Sci-Fi - advanced tech, otherworldly settings', 'assistini'),
                'horror' => __('Horror / Gothic - macabre mood, chiaroscuro', 'assistini'),
                'mythological' => __('Mythological / Historical - period motifs, symbols', 'assistini'),
                'naive-folk' => __('Naïve / Folk - simplified forms, decorative charm', 'assistini')
            ),
        );
    }

    public static function getPlanName($planId = 0) {
        $plans = array(
            1 => __('Free', 'assistini'),
            2 => __('Smart', 'assistini')
        );
        if (isset($plans[$planId]) && !empty($plans[$planId])) {
            return sanitize_text_field($plans[$planId]);
        }
        return sanitize_text_field($plans[1]);
    }

    public static function createRequestId() {
        return 'rq_' . bin2hex(random_bytes(5)) . time();
    }

    public static function getSystemTemplateTranslation($templateId = 0) {
        if ($templateId <= 0) {
            return false;
        }
        $systemTemplates = array(
            1 => array(
                'header' => __('Structured Writing', 'assistini'),
                'info' => __('Step-by-step AI-assisted workflow with detailed prompts across 6 stages to help you plan and write a well-structured blog post.', 'assistini')
            ),
            2 => array(
                'header' => __('Quick Guide', 'assistini'),
                'info' => __('Fast-track your post in just 5 simple AI-powered steps – no overthinking, just results.', 'assistini')
            ),
            3 => array(
                'header' => __('Headline Generation', 'assistini'),
                'info' => __('Generate titles that grab attention and increase clicks.', 'assistini'),
            ),
            4 => array(
                'header' => __('Create subheading', 'assistini'),
                'info' => __('Create attention-grabbing headlines for website or blog post with a specific topic.', 'assistini'),
            ),
            5 => array(
                'header' => __('Intro', 'assistini'),
                'info' => __('Create or rewrite a highly engaging intro for your blog post', 'assistini'),
            ),
            6 => array(
                'header' => __('Paragraph', 'assistini'),
                'info' => __('Add, rewrite or enhance individual paragraphs for your blog post.', 'assistini'),
            ),
            7 => array(
                'header' => __('Content Optimizer', 'assistini'),
                'info' => __('Rewrite and enhance existing content to improve readability and SEO.', 'assistini'),
            ),
            8 => array(
                'header' => __('Text Enricher', 'assistini'),
                'info' => __('Transform brief statements or short sentences into rich, detailed paragraphs to add context or clarity.', 'assistini'),
            ),
            9 => array(
                'header' => __('SEO Title', 'assistini'),
                'info' => __('Optimize your content for search engines with effective meta titles.', 'assistini'),
            ),
            10 => array(
                'header' => __('SEO Description', 'assistini'),
                'info' => __('Create meta descriptions that increase click-through rates.', 'assistini'),
            ),
            11 => array(
                'header' => __('SEO Keywords', 'assistini'),
                'info' => __('Generate relevant keywords to improve SEO.', 'assistini'),
            ),
            12 => array(
                'header' => __('FAQs Generator', 'assistini'),
                'info' => __('Create frequently asked questions based on the content.', 'assistini'),
            ),
            13 => array(
                'header' => __('Q&A Extractor', 'assistini'),
                'info' => __('Turn blog content into engaging questions for community discussions.', 'assistini'),
            ),
            14 => array(
                'header' => __('List & Bullet Point Creator', 'assistini'),
                'info' => __('Convert paragraphs into scannable lists.', 'assistini'),
            ),
            15 => array(
                'header' => __('Summary & Key Takeaways', 'assistini'),
                'info' => __('Add a compelling wrap-up and key takeaways to sum up the content.', 'assistini'),
            ),
            16 => array(
                'header' => __('Call-to-Action Generator', 'assistini'),
                'info' => __('Craft compelling CTAs to drive engagement.', 'assistini'),
            ),
            17 => array(
                'header' => __('Examples & Analogies', 'assistini'),
                'info' => __('Automatically generate examples or analogies to clarify concepts.', 'assistini'),
            ),
            18 => array(
                'header' => __('Check spelling & grammar', 'assistini'),
                'info' => __('Correct mistakes, enhance clarity, and refine your content effortlessly.', 'assistini'),
            ),
            19 => array(
                'header' => __('Create summary', 'assistini')
            ),
            20 => array(
                'header' => __('Expand text', 'assistini')
            ),
            21 => array(
                'header' => __('Rewrite text', 'assistini')
            ),
            22 => array(
                'header' => __('Enhance text', 'assistini')
            ),
            23 => array(),
            25 => array(
                'header' => __('Image Creator', 'assistini'),
                'info' => __('Design and customize images in seconds', 'assistini'),
            ),
            26 => array(
                'header' => __('Image Editor', 'assistini'),
                'info' => __('Modify, refine and perfect your images', 'assistini'),
            ),
            34 => array(
                'header' => __('Podcast Generator', 'assistini'),
                'info' => __('Generate podcasts from text automatically', 'assistini'),
            ),
            35 => array(
                'header' => __('Ask AI', 'assistini'),
                'info' => __('Ask questions and get quick, intelligent answers', 'assistini'),
            ),
        );
        if (is_array($systemTemplates) && isset($systemTemplates[$templateId]) && !empty($systemTemplates[$templateId])) {
            return $systemTemplates[$templateId];
        }
        return false;
    }

    public static function getAllLanguages() {
        return array(
            'af_ZA' => __('Afrikaans', 'assistini'),
            'ar_SA' => __('Arabic', 'assistini'),
            'ar_EG' => __('Arabic (Egypt)', 'assistini'),
            'az_AZ' => __('Azerbaijani', 'assistini'),
            'be_BY' => __('Belarusian', 'assistini'),
            'bn_BD' => __('Bengali', 'assistini'),
            'bg_BG' => __('Bulgarian', 'assistini'),
            'ca_ES' => __('Catalan', 'assistini'),
            'zh_CN' => __('Chinese (Simplified)', 'assistini'),
            'zh_TW' => __('Chinese (Traditional)', 'assistini'),
            'hr_HR' => __('Croatian', 'assistini'),
            'cs_CZ' => __('Czech', 'assistini'),
            'da_DK' => __('Danish', 'assistini'),
            'nl_NL' => __('Dutch', 'assistini'),
            'en_AU' => __('English (Australia)', 'assistini'),
            'en_CA' => __('English (Canada)', 'assistini'),
            'en_IN' => __('English (India)', 'assistini'),
            'en_GB' => __('English (United Kingdom)', 'assistini'),
            'en_US' => __('English (United States)', 'assistini'),
            'et_EE' => __('Estonian', 'assistini'),
            'fi_FI' => __('Finnish', 'assistini'),
            'fr_FR' => __('French', 'assistini'),
            'fr_CA' => __('French (Canada)', 'assistini'),
            'de_DE' => __('German', 'assistini'),
            'de_AT' => __('German (Austria)', 'assistini'),
            'de_CH' => __('German (Switzerland)', 'assistini'),
            'el_GR' => __('Greek', 'assistini'),
            'he_IL' => __('Hebrew', 'assistini'),
            'hi_IN' => __('Hindi', 'assistini'),
            'hu_HU' => __('Hungarian', 'assistini'),
            'is_IS' => __('Icelandic', 'assistini'),
            'id_ID' => __('Indonesian', 'assistini'),
            'it_IT' => __('Italian', 'assistini'),
            'ja_JP' => __('Japanese', 'assistini'),
            'ko_KR' => __('Korean', 'assistini'),
            'lv_LV' => __('Latvian', 'assistini'),
            'lt_LT' => __('Lithuanian', 'assistini'),
            'mk_MK' => __('Macedonian', 'assistini'),
            'ms_MY' => __('Malay', 'assistini'),
            'mr_IN' => __('Marathi', 'assistini'),
            'nb_NO' => __('Norwegian Bokmål', 'assistini'),
            'fa_IR' => __('Persian', 'assistini'),
            'pl_PL' => __('Polish', 'assistini'),
            'pt_PT' => __('Portuguese', 'assistini'),
            'pt_BR' => __('Portuguese (Brazil)', 'assistini'),
            'ro_RO' => __('Romanian', 'assistini'),
            'ru_RU' => __('Russian', 'assistini'),
            'sr_RS' => __('Serbian', 'assistini'),
            'sk_SK' => __('Slovak', 'assistini'),
            'sl_SI' => __('Slovenian', 'assistini'),
            'es_ES' => __('Spanish', 'assistini'),
            'es_MX' => __('Spanish (Mexico)', 'assistini'),
            'sv_SE' => __('Swedish', 'assistini'),
            'ta_IN' => __('Tamil', 'assistini'),
            'te_IN' => __('Telugu', 'assistini'),
            'th_TH' => __('Thai', 'assistini'),
            'tr_TR' => __('Turkish', 'assistini'),
            'uk_UA' => __('Ukrainian', 'assistini'),
            'vi_VN' => __('Vietnamese', 'assistini'),
            'cy_GB' => __('Welsh', 'assistini'),
            'zu_ZA' => __('Zulu', 'assistini'),
        );
    }

    public static function getErrorTranslation($error = '') {
        $errors = array(
            'nonce' => __('WordPress Session Timeout: For security reasons, WordPress automatically ends your current session if your website has been inactive for a while. Please reload this page to continue your work.', 'assistini'),
            'default' => __('Something went wrong with the AI server request - please retry.', 'assistini'),
            'missing_blog_user_token' => __('Something went wrong (missing user_token). Please reload the page and try again.', 'assistini'), //Missing blog user token
            'missing_blog_access_token' => __('Something went wrong (missing access_token). Please reload the page and try again.', 'assistini'), //Missing blog access token
            'missing_blog_identifier' => __('Something went wrong (missing blog_ident). Please reload the page and try again.', 'assistini'), //Missing blog identifier
            'missing_blog_url' => __('Something went wrong (missing blog_url). Please reload the page and try again.', 'assistini'), //Missing blog url
            'missing_blog_user_id' => __('Something went wrong (missing user_id). Please reload the page and try again.', 'assistini'), //Missing blog user id
            'blog_user_token_invalid' => __('Something went wrong (invalid user_token). Please reload the page and try again.', 'assistini'), //Invalid blog user token
            'missing_request_id' => __('Something went wrong (missing request_id). Please reload the page and try again.', 'assistini'), //Missing request id
            'missing_user_id' => __('Something went wrong (missing user_id). Please reload the page and try again.', 'assistini'), //Missing user id
            'missing_template_id' => __('Something went wrong (missing template_id). Please reload the page and try again.', 'assistini'), //Missing template id
            'missing_session_id' => __('Something went wrong (missing session_id). Please reload the page and try again.', 'assistini'), //Missing session id
            'missing_plugin_version' => __('Something went wrong (missing plugin_version). Please reload the page and try again.', 'assistini'), //Missing plugin version
            'no_enough_quota' => __('Your usage limit has been reached. Please check your quota and upgrade your plan to continue.', 'assistini'),
            'chat_limit_reached' => __('You\'ve reached the chat limit. Please upgrade your plan to continue.', 'assistini'),
            'chat_disabled_please_upgrade_plan' => __('Your chat is currently disabled. Please upgrade your plan to continue.', 'assistini'),
            'no_template_found' => __('No matching template found. Please check your selection.', 'assistini'),
            'invalid_url' => __('The provided URL is not valid. Please enter a valid url.', 'assistini'),
            'no_permissions_to_use' => __('You do not have permission to perform this action. Please inform your administrator to resolve this permission problem.', 'assistini'),
            'no_chat_permissions' => __('Your chat access is currently restricted. Please check your permissions.', 'assistini'),
            'no_permissions_to_edit' => __('You do not have permission to edit this template. Please check your permissions.', 'assistini'),
            'template_disabled_please_upgrade_plan' => __('This template is disabled. Please upgrade your plan to use it.', 'assistini'),
            'insufficient_plan' => __('Your current plan does not support this action. Please upgrade your plan.', 'assistini'),
            'session_not_found' => __('Something went wrong (missing session). Please reload the page and try again.', 'assistini'),
            'assistini_connection_broken' => __('Your connection to Assistini is invalid. Please reconnect your account.', 'assistini'),
            'no_assistini_account_connected' => __('No Assistini account is connected. Please connect your account first.', 'assistini'),
            'wrong_input_format' => __('The format of your input is not valid. Please check your entry.', 'assistini'),
            'prompt_does_not_exist' => __('The selected prompt could not be found. Please check your entry.', 'assistini'),
            'prompt_not_ready' => __('The prompt is not ready yet. Please try again.', 'assistini'),
            'missing_user_input' => __('Please enter your input to continue.', 'assistini'),
            'missing_user_prompt' => __('Please enter your prompt to continue.', 'assistini'),
            'missing_prompt_language' => __('Please select a language to continue.', 'assistini'),
            'missing_content' => __('Content is missing. Please provide the required text.', 'assistini'),
            'missing_number_of_results' => __('Please specify how many results you want.', 'assistini'),
            'missing_focus_keyword' => __('Please enter a focus keyword.', 'assistini'),
            'missing_additional_content' => __('Please provide additional content.', 'assistini'),
            'missing_input' => __('Input is missing. Please check your entry.', 'assistini'),
            'missing_image' => __('Please upload an image.', 'assistini'),
            'missing_email' => __('Please enter your email address.', 'assistini'),
            'missing_name' => __('Please enter your name.', 'assistini'),
            'missing_message' => __('Please enter your message.', 'assistini'),
            'invalid_email' => __('The email address you entered is not valid.', 'assistini'),
            'custom_api_key_already_set' => __('The provided API key is already set. Please check your settings.', 'assistini'),
            'custom_api_openai_key_invalid' => __('Your OpenAI API key is invalid. Please verify the key and try again.', 'assistini'),
            'custom_api_openai_key_insufficient_quota' => __('Your OpenAI API key has run out of quota. Please check your usage or upgrade your OpenAI plan to continue.', 'assistini'),
            'content_policy_violation' => __('This content violates the OpenAI usage policy. Please adjust your inputs.', 'assistini'),
            'client_timeout' => __('The request took too long. Please try again.', 'assistini'),
            'client_blocked' => __('Your request was blocked for security reasons. Please try again later.', 'assistini'),
            'server_auth_failed' => __('Authentication with the server failed. Please check your connection and try again.', 'assistini'),
            'server_blocked' => __('The server has blocked this request. Please try again or contact support if the issue persists.', 'assistini'),
            'gemini_image_generation_failed_by_prompt' => __('Currently, Gemini couldn\'t generate your image. Please try adjusting your prompt and try again.', 'assistini'),
            'image_not_found' => __('The provided image is invalid.', 'assistini'),
            'invalid_mime_type' => __('The mime type of the provided image is not supported.', 'assistini'),
            'image_size_limit' => __('The provided image is larger than the supported 3MB', 'assistini'),
            'missing_permission' => __('Your user has insuffient permissions for this action.', 'assistini'),
        );
        $error = strtolower($error);
        if (isset($errors[$error]) && !empty($errors[$error])) {
            return sanitize_text_field($errors[$error]);
        }
        return sanitize_text_field($errors['default']);
    }

    public static function getModelTranslations() {
        return array(
            'gpt-image-1' => 'GPT-Image 1',
            'gemini-2.5-flash-image' => 'Gemini 2.5 Flash Image',
        );
    }

    /**
     * Sanitizes an array|object of data. Automatically converts inner json strings to arrays|objects.
     * @param array|object $data The array|object to sanitize.
     * @return array|object The sanitized array|object.
     */
    public static function sanitizeArrayOrObject($data = array(), $allowBr = false) {
        $isObject = is_object($data);
        try {
            if ($isObject) {
                $data = (array) $data;
            }
            if (!is_array($data) || empty($data)) {
                return array();
            }
            $sanitized = array();
            foreach ($data as $key => $value) {
                $sanitizedKey = sanitize_key($key);
                if (is_bool($value)) {
                    $sanitized[$sanitizedKey] = (bool) $value;
                } else if (is_numeric($value) || is_int($value)) {
                    $sanitized[$sanitizedKey] = (int) $value;
                } else if (is_array($value) || is_object($value)) {
                    $sanitized[$sanitizedKey] = self::sanitizeArrayOrObject($value);
                } else {
                    $json_decoded = json_decode($value, $isObject ? false : true);
                    if (json_last_error() === JSON_ERROR_NONE && (is_array($json_decoded) || is_object($json_decoded))) {
                        $sanitized[$sanitizedKey] = self::sanitizeArrayOrObject($json_decoded);
                    } else {
                        if (strpos($value, "<br />") !== false || strpos($value, "<br>") !== false || strpos($value, "<br/>") !== false) {
                            $sanitized[$sanitizedKey] = wp_kses($value, array('br' => array()));
                        } else if (strpos($value, "\n") !== false || strpos($value, "\r") !== false) {
                            $sanitized[$sanitizedKey] = sanitize_textarea_field(wp_unslash($value));
                        } else {
                            $sanitized[$sanitizedKey] = sanitize_text_field(wp_unslash($value));
                        }
                    }
                }
            }
            return $isObject ? (object) $sanitized : $sanitized;
        } catch (Exception $e) {
            return $isObject ? (object) array() : array();
        }
    }
}
