<?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;

        /**
         * Get Class Instance
         * @return PWH_DCFH_Helpers
         */
        public static function instance()
        {
            if (self::$_instance == null) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }

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

        /**
         * Log Data
         *
         * @param $data
         * @param false $delete
         * @param string $filename
         */
        public static function log($data, $delete = false, $filename = '')
        {
            // phpcs:disable
            if (empty($filename)) {
                $filename = debug_backtrace()[1]['function'];
            }
            $filename = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$filename.'.log';
            if (file_exists($filename) && $delete) {
                wp_delete_file($filename);
            }
            ini_set('error_log', $filename);
            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 $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 $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_bot()
        {
            $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()
        {
            if (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip_address = sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
            } else {
                if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $ip_address = sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);
                } else {
                    if (isset($_SERVER['HTTP_X_FORWARDED'])) {
                        $ip_address = sanitize_text_field($_SERVER['HTTP_X_FORWARDED']);
                    } else {
                        if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
                            $ip_address = sanitize_text_field($_SERVER['HTTP_FORWARDED_FOR']);
                        } else {
                            if (isset($_SERVER['HTTP_FORWARDED'])) {
                                $ip_address = sanitize_text_field($_SERVER['HTTP_FORWARDED']);
                            } else {
                                if (isset($_SERVER['REMOTE_ADDR'])) {
                                    $ip_address = sanitize_text_field($_SERVER['REMOTE_ADDR']);
                                } else {
                                    $ip_address = __('IP not found', 'pwh-dcfh');
                                }
                            }
                        }
                    }
                }
            }

            return $ip_address;
        }

        /**
         * 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 (preg_match('/linux/i', $user_agent)) {
                $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 (preg_match('/MSIE/i', $user_agent) && !preg_match('/Opera/i', $user_agent)) {
                $browser = esc_html('Internet Explorer');
                $user_browser = esc_html('MSIE');
            } elseif (preg_match('/Firefox/i', $user_agent)) {
                $browser = esc_html('Mozilla Firefox');
                $user_browser = esc_html('Firefox');
            } elseif (preg_match('/Chrome/i', $user_agent)) {
                $browser = esc_html('Google Chrome');
                $user_browser = esc_html('Chrome');
            } elseif (preg_match('/Safari/i', $user_agent)) {
                $browser = esc_html('Apple Safari');
                $user_browser = esc_html('Safari');
            } elseif (preg_match('/Opera/i', $user_agent)) {
                $browser = esc_html('Opera');
                $user_browser = esc_html('Opera');
            } elseif (preg_match('/Netscape/i', $user_agent)) {
                $browser = esc_html('Netscape');
                $user_browser = esc_html('Netscape');
            }
            $known = ['Version', $user_browser, 'other'];
            $pattern = '#(?<browser>'.join('|', $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
            $number = 0;
            if (isset($matches[1])) {
                $number = $matches[1];
            }

            return $number;
        }

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

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

            return isset($match[0]) ? $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+):\"(.*?)\";/', 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 $key
         *
         * @return array|mixed
         */
        public static function csv_fixed_fields($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;
        }

        /**
         * Custom Linebreak
         *
         * @param $string
         * @param $linebreaks
         * @param $xml
         *
         * @return string
         */
        public static function nl2p($string, $linebreaks = true, $xml = true)
        {
            $string = str_replace(['<p>', '</p>', '<br>', '<br />'], '', $string);
            if ($linebreaks) {
                $string = '<p>'.preg_replace(["/([\n]{2,})/i", "/([^>])\n([^<])/i"], ["</p>\n<p>", '$1<br'.($xml ? ' /' : '').'>$2'], trim($string)).'</p>';

            } else {
                $string = '<p>'.preg_replace(["/([\n]{2,})/i", "/([\r\n]{3,})/i", "/([^>])\n([^<])/i"], ["</p>\n<p>", "</p>\n<p>", '$1<br'.($xml ? ' /' : '').'>$2'], trim($string)).'</p>';
            }

            return $string;
        }
    }
}