<?php

class Bug_Monitor_Helper {

      public static $db;

      public static function init(){
            self::$db = $GLOBALS['wpdb'];
            self::$db->bug_monitor_hits = self::$db->prefix . 'bug_monitor_hits';
            self::$db->bug_monitor_events = self::$db->prefix . 'bug_monitor_events';
            self::$db->bug_monitor_sessions = self::$db->prefix . 'bug_monitor_sessions';
            self::$db->bug_monitor_screenshots = self::$db->prefix . 'bug_monitor_screenshots';

      }

      public static function get_url_origin($url){
            $home_url = home_url();
            if (parse_url($url, PHP_URL_HOST) != parse_url($home_url, PHP_URL_HOST)){
                  return sprintf(__('3rd party URL: (%s)', 'bug-monitor'), $url);
            }

            $scheme = parse_url($home_url, PHP_URL_SCHEME);
            $url = (parse_url($url, PHP_URL_SCHEME) == '' ? $scheme . $url : $url);
            $file_path = str_replace($home_url, ABSPATH, $url);

            return self::get_file_origin($file_path);
      }

      public static function get_file_origin($file_path) {
            $file_path = wp_normalize_path($file_path);
            $content_dir = wp_normalize_path(WP_CONTENT_DIR);
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
            $all_plugins = get_plugins();
            foreach ($all_plugins as $plugin_path => $plugin_data) {
                  if (strpos($file_path, WP_PLUGIN_DIR . '/' . dirname($plugin_path) . '/') === 0) {
                        return sprintf(__('%s file', 'bug-monitor'), $plugin_data['Name']);
                  }
            }
            $theme_dir = wp_normalize_path(get_theme_root());
            if (strpos($file_path, $theme_dir) === 0) {
                  $relative_path = str_replace($theme_dir, '', $file_path);
                  $theme_folder = trim(current(explode('/', trim($relative_path, '/'))), '/');
                  $style_css_path = trailingslashit($theme_dir) . trailingslashit($theme_folder) . 'style.css';

                  if (file_exists($style_css_path)) {
                        $theme_data = get_file_data($style_css_path, array('ThemeName' => 'Theme Name'));
                        $theme_name = $theme_data['ThemeName'];

                        if (!empty($theme_name)) {
                              return sprintf(__('%s file', 'bug-monitor'), $theme_name);
                        }
                        else {
                              return __('Theme file', 'bug-monitor');
                        }
                  }
            }
            $wp_core_files = ['wp-admin', 'wp-includes', 'wp-config.php', 'wp-cron.php'];
            $abspath = wp_normalize_path(ABSPATH);
            foreach ($wp_core_files as $file) {
                  if (strpos($file_path, $abspath . $file) === 0) {
                        return __('WP Core file', 'bug-monitor');
                  }
            }
            return __('3rd party file', 'bug-monitor');
      }

      public static function get_file_type($file){
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

            switch ($extension) {
                  case 'png':
                  case 'jpg':
                  case 'jpeg':
                  case 'gif':
                        case 'svg':
                        case 'webp':
                        case 'avif':
                              return __('image', 'bug-monitor');
                              break;
                              case 'mp4':
                              case 'webm':
                              case 'ogv':
                              return __('video', 'bug-monitor');
                              break;
                              case 'css':
                              return __('stylesheet', 'bug-monitor');
                              break;
                              case 'js':
                              return __('javascript', 'bug-monitor');
                              break;
                              default:
                              return '';
                              break;
            }
      }

      public static function get_device_data($useragent, $return = 'string') {
            $useragent = strtolower($useragent);
            $device = 'Unknown Device';
            $browser = 'Unknown Browser';

            if (empty($useragent)){
                  $device = 'Server';
                  $browser = 'CLI';
            }

            // WordPress
            if (preg_match('~^WordPress\/([\d\.]+);~i', $useragent)){
                  $device = 'Server';
                  $browser = 'WordPress';
            }

            // Apple devices
            if (strpos($useragent, 'iphone') !== false) $device = 'iPhone';
            elseif (strpos($useragent, 'ipod') !== false) $device = 'iPod';
            elseif (strpos($useragent, 'ipad') !== false) $device = 'iPad';
            elseif (strpos($useragent, 'macintosh') !== false || strpos($useragent, 'mac os') !== false) $device = 'MacOS';

            // Android devices
            elseif (strpos($useragent, 'android') !== false) {
                  $device = (strpos($useragent, 'mobile') !== false) ? 'Android Phone' : 'Android Tablet';
            }

            // Windows devices
            elseif (strpos($useragent, 'windows phone') !== false) $device = 'Windows Phone';
            elseif (strpos($useragent, 'windows') !== false) $device = 'Windows Desktop';

            // Other devices
            elseif (strpos($useragent, 'blackberry') !== false) $device = 'BlackBerry';
            elseif (strpos($useragent, 'kindle') !== false) $device = 'Kindle';
            elseif (strpos($useragent, 'linux') !== false) $device = 'Linux Desktop';
            elseif (strpos($useragent, 'ubuntu') !== false) $device = 'Ubuntu Desktop';

            // Browsers
            if (preg_match('/msie (\\d+)/', $useragent, $matches) || preg_match('/trident.*rv:(\\d+)/', $useragent, $matches)) {
                  $browser = 'Internet Explorer ' . $matches[1];
            } elseif (preg_match('/firefox\\/(\\d+)/', $useragent, $matches)) {
                  $browser = 'Firefox ' . $matches[1];
            } elseif (preg_match('/safari\\/(\\d+)/', $useragent, $matches) && strpos($useragent, 'chrome') === false) {
                  $browser = 'Safari ' . $matches[1];
            } elseif (preg_match('/opera|opr\\/(\\d+)/', $useragent, $matches)) {
                  $browser = 'Opera ' . $matches[1];
            } elseif (preg_match('/edge?\\/([\\d]+)/', $useragent, $matches)) {
                  $browser = 'Edge ' . $matches[1];
            } elseif (preg_match('/chrome\\/(\\d+)/', $useragent, $matches)) {
                  $browser = 'Chrome ' . $matches[1];
            }

            // In-app browsers
            elseif (strpos($useragent, 'fbav') !== false) $browser = 'Facebook In-App Browser';
            elseif (strpos($useragent, 'twitter') !== false) $browser = 'Twitter In-App Browser';
            elseif (strpos($useragent, 'instagram') !== false) $browser = 'Instagram In-App Browser';

            if ($return == 'string'){
                  return "$device, $browser";
            }
            else {
                  return array(
                        'device' => $device,
                        'browser' => $browser
                  );
            }
      }

      public static function get_device_icons($useragent) {
            $icons = $browser = '';
            $device = $os = array();
            $device_data = self::get_device_data($useragent, 'array');
            if (strpos(strtolower($device_data['device']), 'phone') !== false){
                  $device = array('mobile.svg', esc_html__('Phone', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'tablet') !== false){
                  $device = array('tablet.svg', esc_html__('Tablet', 'bug-monitor'));
            }
            else if ($device_data['device'] == 'iPad'){
                  $device = array('tablet.svg', esc_html__('iPad', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'desktop') !== false){
                  $device = array('desktop.svg', esc_html__('Desktop', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'macos') !== false){
                  $device = array('desktop.svg', esc_html__('Mac', 'bug-monitor'));
                  $os = array('apple.svg', esc_html__('MacOS', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'server') !== false){
                  $device = array('server.svg', esc_html__('Server', 'bug-monitor'));
                  if (stristr(PHP_OS, 'DAR')) {
                        $os = array('apple.svg', esc_html__('MacOS', 'bug-monitor'));
                  }
                  else if (stristr(PHP_OS, 'WIN')) {
                        $os = array('windows.svg', esc_html__('Windows', 'bug-monitor'));
                  }
                  else if (stristr(PHP_OS, 'LINUX')) {
                        $os = array('linux.svg', esc_html__('Linux', 'bug-monitor'));
                  }
                  else {
                        $os = array('unknown.svg', esc_html__('Unknown OS', 'bug-monitor'));
                  }
            }
            else if ($device_data['device'] == 'Unknown Device') {
                  $device = array('unknown.svg', esc_html__('Unknown Device', 'bug-monitor'));
            }

            if (preg_match('~i(Phone|Pad|Pod)~', $device_data['device'])){
                  $os = array('apple.svg', esc_html__('iOS', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'android') !== false){
                  $os = array('android.svg', esc_html__('Android', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'windows') !== false){
                  $os = array('windows.svg', esc_html__('Windows', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'ubuntu') !== false){
                  $os = array('ubuntu.svg', esc_html__('Ubuntu', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'linux') !== false){
                  $os = array('linux.svg', esc_html__('Linux', 'bug-monitor'));
            }
            else if (strpos(strtolower($device_data['device']), 'blackberry') !== false){
                  $os = array('blackberry.svg', esc_html__('Blackberry', 'bug-monitor'));
            }

            if (strpos($device_data['browser'], 'Firefox') !== false) {
                  $browser = 'firefox.svg';
            }
            else if (strpos($device_data['browser'], 'Safari') !== false) {
                  $browser = 'safari.svg';
            }
            else if (strpos($device_data['browser'], 'Opera') !== false) {
                  $browser = 'opera.svg';
            }
            else if (strpos($device_data['browser'], 'Edge') !== false) {
                  $browser = 'edge.svg';
            }
            else if (strpos($device_data['browser'], 'Chrome') !== false) {
                  $browser = 'chrome.svg';
            }
            else if (strpos($device_data['browser'], 'Facebook') !== false) {
                  $browser = 'facebook.svg';
            }
            else if (strpos($device_data['browser'], 'Twitter') !== false) {
                  $browser = 'twitter.svg';
            }
            else if (strpos($device_data['browser'], 'Instagram') !== false) {
                  $browser = 'instagram.svg';
            }
            else if ($device_data['browser'] == 'CLI') {
                  $browser = 'cli.svg';
            }
            else if ($device_data['browser'] == 'WordPress') {
                  $browser = 'wordpress.svg';
            }
            else if ($device_data['browser'] == esc_html__('Unknown Browser', 'bug-monitor')) {
                  $browser = 'unknown.svg';
            }


            if (!empty($device)){
                  $icons .= '<span><img src="' . BUG_MONITOR_PLUGIN_URL . 'images/icons/' . $device[0] . '">' . $device[1] . '</span>';
            }
            if (!empty($os)){
                  $icons .= '<span><img src="' . BUG_MONITOR_PLUGIN_URL . 'images/icons/' . $os[0] . '">' . $os[1] . '</span>';
            }
            if (!empty($browser)){
                  $icons .= '<span><img src="' . BUG_MONITOR_PLUGIN_URL . 'images/icons/' . $browser . '">' . $device_data['browser'] . '</span>';
            }

            return $icons;

      }

      public static function is_touch_device($useragent) {
          $useragent = strtolower($useragent);
          if (strpos($useragent, 'iphone') !== false ||
              strpos($useragent, 'ipod') !== false ||
              strpos($useragent, 'ipad') !== false ||
              strpos($useragent, 'android') !== false && strpos($useragent, 'mobile') !== false ||
              strpos($useragent, 'windows phone') !== false ||
              strpos($useragent, 'blackberry') !== false ||
              strpos($useragent, 'kindle') !== false) {
              return true;
          }

          return false;
      }


      public static function get_dashbord_url(){
            return add_query_arg('page', 'bug-monitor', admin_url('tools.php'));
      }

      public static function get_template($template, $data = array()){
            if (file_exists(BUG_MONITOR_PLUGIN_DIR . 'templates/' . $template . '.tpl.php')){
                  ob_start();
                  include BUG_MONITOR_PLUGIN_DIR . 'templates/' . $template . '.tpl.php';
                  return ob_get_clean();
            }

            return '';
      }

      public static function get_icon($icon){
            return file_get_contents(BUG_MONITOR_PLUGIN_DIR . 'images/icons/' . $icon . '.svg');
      }

      public static function get_link_tag($url, $text = ''){
            $text = (!empty($text) ? $text : $url);
            return '<a href="' . esc_url($url) . '" target="_blank">' . $text . '</a>';
      }

      public static function get_current_url(){
            if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])){
                  return (is_ssl() ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            }

            return '';
      }

      public static function choose_article($word) {
            if (empty($word)){
                  return '';
            }

            $first_letter = strtolower($word[0]);
            $vowels = ['a', 'e', 'i', 'o', 'u'];

            if (in_array($first_letter, $vowels)) {
                  return __('an', 'bug-monitor');
            } else {
                  return __('a', 'bug-monitor');
            }
      }

      public static function is_admin(){
            return (is_admin() || (isset($_SERVER['REQUEST_URI']) && parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) == parse_url(wp_login_url(), PHP_URL_PATH)));
      }

      public static function maybe_checked($option, $value = 'on'){
            echo (Bug_Monitor::check_option($option, $value) ? ' checked' : '');
      }

      public static function maybe_selected($option, $value = 'on'){
            echo (Bug_Monitor::check_option($option, $value) ? ' selected' : '');
      }
      public static function str2number($string){
            if (strpos($string, '.') !== false){
                  return (float)$string;
            }
            else {
                  return (int)$string;
            }
      }

      public static function truncate_str($str, $max_length = 100){
            return (strlen($str) > $max_length ? substr($str, 0, $max_length - 3) . '...' : $str);
      }
      public static function normalize_url($url){
            return preg_replace('~[/#]+$~', '', $url);
      }

      public static function gz($data){
            return base64_encode(gzencode($data, 9));
      }

      public static function ugz($data){
            if (empty($data)){
                  return '';
            }
            return @gzdecode(base64_decode($data));
      }

      public static function decode($string){
            $encoded = base64_decode($string);
            $decoded = '';
            $length = strlen($encoded);

            for ($i = 0; $i < $length; $i++) {
                  $char = $encoded[$i];
                  $num = ord($char);
                  $num -= 3;
                  $decoded .= chr($num);
            }

            return $decoded;
      }
}

Bug_Monitor_Helper::init();

?>