<?php

namespace PWH_DCFH\App\Helpers;

if (!defined('ABSPATH')) {
    exit;
}
if (!function_exists('get_plugin_data')) {
    require_once(ABSPATH.'wp-admin/includes/plugin.php');
}
if (!class_exists('PWH_DCFH_Helpers')) {
    class PWH_DCFH_Helpers
    {
        private static $_instance;

        /**
         * Returns the singleton instance of the class.
         * @return self
         */
        public static function instance()
        {
            if (self::$_instance === null) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }

        /**
         * Print Data
         *
         * @param string|null $data
         * @param false $exit
         */
        public static function dd($data = '', $exit = true)
        {
            // phpcs:disable
            echo "<pre>";
            print_r($data);
            echo "</pre>";
            if ($exit) {
                exit;
            }
            // phpcs:enable
        }

        /**
         * Log Data
         *
         * @param $data
         * @param bool $delete
         * @param string $filename
         */
        public static function log($data, $delete = false, $filename = '')
        {
            // phpcs:disable
            if (empty($filename)) {
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
                $filename = isset($trace[1]['function']) ? $trace[1]['function'] : time();
            }
            $filename = sanitize_file_name($filename).'.log';
            $filepath = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$filename;
            if ($delete && file_exists($filepath)) {
                wp_delete_file($filepath);
            }
            ini_set('error_log', $filepath);
            if (is_array($data) || is_object($data)) {
                error_log(print_r($data, true));
            } else {
                error_log($data);
            }
            // phpcs:enable
        }

        /**
         * Get Current Page Name
         * @return string|null
         */
        public static function current_page()
        {
            return isset($_GET['page']) ? sanitize_text_field($_GET['page']) : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No need to use nonce.
        }

        /**
         * Clean String
         *
         * @param $string
         * @param string $case
         *
         * @return mixed
         */
        public static function sanitize_string($string, $case = 'ucwords')
        {
            // Remove Accents
            $string = remove_accents($string);
            // Replace Underscore and Hyphen
            $string = preg_replace('/[\-_]/', ' ', $string);
            // Removes special chars with space
            $string = preg_replace('/\W/', ' ', $string);
            // Replacing multiple spaces with a single space
            $string = preg_replace('!\s+!', ' ', $string);
            // Trim Spaces
            $string = trim($string);
            if (empty($case) || ' ' === $case) {
                $case = 'strtolower';
            }

            return call_user_func($case, $string);
        }

        /**
         * Sanitize String To Key
         *
         * @param $string
         * @param string $replace_with
         *
         * @return string
         */
        public static function sanitize_key($string, $replace_with = '_')
        {
            $string = remove_accents($string);
            // Removes special chars with space
            $string = preg_replace('/\W/', ' ', $string);
            // Replacing multiple spaces with a single space
            $string = preg_replace('!\s+!', ' ', $string);
            // Trim Spaces
            $string = trim($string);
            // Replace space
            $string = str_replace(' ', $replace_with, $string);

            return strtolower($string);
        }

        /**
         * Encrypt/Decrypt
         *
         * @param string $string
         * @param string $encrypt_decrypt
         *
         * @return false|string|null
         */
        public static function encrypt_decrypt($string = '', $encrypt_decrypt = 'e')
        {
            $output = null;
            $secret_key = 'wbtZKk}rohV^Uw7V?+pgtNG++R2@hT3La.A)u*8+MK]-l?pM&,lfs{79SvXu/';
            $secret_iv = 'w}W<<gj~+$S.TzRZ,=n*P@B{Ma{MnR(0baJ<zU|V7wCvl)&gC@4%+pth_-=|jRJo';
            $key = hash('sha256', $secret_key);
            $iv = substr(hash('sha256', $secret_iv), 0, 16);
            if ($encrypt_decrypt === 'e') {
                $output = base64_encode(openssl_encrypt($string, "AES-256-CBC", $key, 0, $iv)); // phpcs:ignore
            } elseif ($encrypt_decrypt === 'd') {
                $output = openssl_decrypt(base64_decode($string), "AES-256-CBC", $key, 0, $iv); // phpcs:ignore
            }

            return $output;
        }

        /**
         * Check Is BOT?
         * @return false|int
         */
        public static function is_robot()
        {
            $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';
            if (!empty($user_agent)) {
                return preg_match('/abacho|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|bot|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|-google|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD-Explorer|KIT-Fireball|ko_yappo_robot|label-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|MJ12bot|mod_pagespeed|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan-online|nil|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp-info-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww-perl|verticrawl|Victoria|void-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|webs|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus/i', $user_agent);
            }

            return false;
        }

        /**
         * Get IP Address
         * @return string
         */
        public static function get_ip_address()
        {
            // Array of potential IP headers in the order of priority
            $headers = [
                'HTTP_CLIENT_IP',
                'HTTP_X_FORWARDED_FOR',
                'HTTP_X_FORWARDED',
                'HTTP_FORWARDED_FOR',
                'HTTP_FORWARDED',
                'REMOTE_ADDR'
            ];
            foreach ($headers as $header) {
                if (isset($_SERVER[$header])) {
                    return sanitize_text_field($_SERVER[$header]);
                }
            }

            return __('IP not found', 'pwh-dcfh');
        }

        /**
         * Get User Agent
         * @return array|null
         */
        public static function get_user_agent($agent = '')
        {
            $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : null;
            if (empty($user_agent)) {
                return null;
            }
            $browser = __('Browser not found', 'pwh-dcfh');
            $platform = __('Platforn not found', 'pwh-dcfh');
            $user_browser = "";
            if (false !== stripos($user_agent, "linux")) {
                $platform = esc_html('linux');
            } elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
                $platform = esc_html('mac');
            } elseif (preg_match('/windows|win32/i', $user_agent)) {
                $platform = esc_html('windows');
            }
            if (false !== stripos($user_agent, "MSIE") && false === stripos($user_agent, "Opera")) {
                $browser = esc_html('Internet Explorer');
                $user_browser = esc_html('MSIE');
            } elseif (false !== stripos($user_agent, "Firefox")) {
                $browser = esc_html('Mozilla Firefox');
                $user_browser = esc_html('Firefox');
            } elseif (false !== stripos($user_agent, "Chrome")) {
                $browser = esc_html('Google Chrome');
                $user_browser = esc_html('Chrome');
            } elseif (false !== stripos($user_agent, "Safari")) {
                $browser = esc_html('Apple Safari');
                $user_browser = esc_html('Safari');
            } elseif (false !== stripos($user_agent, "Opera")) {
                $browser = esc_html('Opera');
                $user_browser = esc_html('Opera');
            } elseif (false !== stripos($user_agent, "Netscape")) {
                $browser = esc_html('Netscape');
                $user_browser = esc_html('Netscape');
            }
            $known = ['Version', $user_browser, 'other'];
            $pattern = '#(?<browser>'.implode('|', $known).')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
            if (preg_match_all($pattern, $user_agent, $matches)) {
                $i = count($matches['browser']);
                if ($i !== 1) {
                    if (strripos($user_agent, 'Version') < strripos($user_agent, $user_browser)) {
                        $version = $matches['version'][0];
                    } else {
                        $version = $matches['version'][1];
                    }
                } else {
                    $version = $matches['version'][0];
                }
                if ($version === null || $version === '') {
                    $version = '';
                }
                $data = [
                    'agent' => $user_agent,
                    'browser' => $browser,
                    'version' => $version,
                    'platform' => $platform,
                ];
                if (!empty($agent) && isset($data[$agent])) {
                    return $data[$agent];
                }

                return $data;
            }

            return null;
        }

        /**
         * Get Number From String
         *
         * @param $string
         *
         * @return int
         */
        public static function get_number_from_string($string)
        {
            preg_match('/et_pb_contact_field_(\d{1,12})/', $string, $matches); // Extract Field ID

            return $matches[1] ?? 0;
        }

        /**
         * Get Field Index
         *
         * @param $string
         *
         * @return string
         */
        public static function get_field_index($string)
        {

            preg_match("|\d+|", $string, $match);

            return $match[0] ?? '';
        }

        /**
         * Unserialize String And Fixed String If Error In String
         *
         * @param $string
         *
         * @return mixed|string
         */
        public static function maybe_unserialize($string)
        {
            $string = wp_specialchars_decode($string);
            $unserialize_data = maybe_unserialize($string);
            if (false === $unserialize_data) {
                $string = preg_replace_callback('/s:(\d+):\"(.*?)\";/', static function ($matches) use ($string) {
                    if (isset($matches[2])) {
                        return "s:".strlen($matches[2]).':"'.$matches[2].'";';
                    }

                    return $string;
                }, $string);
                $unserialize_data = maybe_unserialize($string);
            }

            return $unserialize_data;
        }

        /**
         * Get CSV Fixed Fields
         *
         * @param string $key
         *
         * @return array|mixed
         */
        public static function fixed_form_placeholders($key = '')
        {
            $fields = [
                'entry_number' => __('Entry Number', 'pwh-dcfh'),
                'read_by' => __('Read By', 'pwh-dcfh'),
                'submitter' => __('Submitter', 'pwh-dcfh'),
                'page_title' => __('Page Title', 'pwh-dcfh'),
                'page_url' => __('Page URL', 'pwh-dcfh'),
                'date' => __('Date', 'pwh-dcfh'),
                'ip_address' => __('IP Address', 'pwh-dcfh'),
                'browser' => __('Browser', 'pwh-dcfh'),
                'platform' => __('Platform', 'pwh-dcfh')
            ];
            if ('' !== $key && isset($fields[$key])) {
                return $fields[$key];
            }

            return $fields;
        }

        /**
         * Fixed Site placeholders
         * @return string[]
         */
        public static function fixed_site_placeholders()
        {
            return [
                'dcfh_post_title',
                'dcfh_post_url',
                'dcfh_site_name',
                'dcfh_site_url',
                'dcfh_admin_email'
            ];
        }

        /**
         * To Copy As
         * @return array
         */
        public static function get_post_clone_types()
        {
            return [
                '' => __('Please Select', 'pwh-dcfh'),
                'title' => __('Title', 'pwh-dcfh'),
                'content' => __('Content', 'pwh-dcfh'),
                'featured_image' => __('Featured Image', 'pwh-dcfh'),
                'custom_field' => __('Custom Field', 'pwh-dcfh'),
            ];
        }
    }
}