<?php


class Bug_Monitor_Config {

      public static $db_version = 1.1;

      public static $triggers = array(
            'network/http',
            'network/mixed_content',
            'network/csp',
            'network/insecure',
            'seo/title',
            'seo/description',
            'seo/image',
            'ux/non_responsive_element',
            'ux/slow_response',
            'ux/bounce_rate',
            'ui/too_close_clickable',
            'ui/hard_read_text',
            'ui/layout',
            'ui/content_obstruction',
            'ui/font',
            'js/error',
            'webvitals/lcp',
            'webvitals/fcp',
            'webvitals/cls',
            'functional/non_responsive_button',
            'functional/form_submission',
            'functional/form_abandonment',
            'functional/broken_link',
      );

      public static $settings = array(
          'network/http' => 'on',
          'network/mixed_content' => 'on',
          'network/csp' => 'on',
          'network/insecure' => 'on',
          'seo/title' => 'on',
          'seo/description' => 'on',
          'seo/image' => 'on',
          'ux/non_responsive_element' => 'on',
          'ux/slow_response' => 'on',
          'ux/bounce_rate' => 'on',
          'ui/too_close_clickable' => 'on',
          'ui/hard_read_text' => 'on',
          'ui/layout' => 'on',
          'ui/content_obstruction' => 'on',
          'ui/font' => 'on',
          'js/error' => 'on',
          'webvitals/lcp' => 'on',
          'webvitals/fcp' => 'on',
          'webvitals/cls' => 'on',
          'functional/non_responsive_button' => 'on',
          'functional/form_submission' => 'on',
          'functional/form_abandonment' => 'on',
          'functional/broken_link' => 'on',
          'php/error' => 'on',
          'php/warning' => '',
          'php/deactivate_plugin' => '',
          'php/redirect_loop' => 'on',
          'php/malicious_redirect' => 'on',
          'php/email_sending_error' => 'on',
          'server/uptime' => '',
          'system/disable_toolbar' => '',
          'system/event_retention' => '30',
          'notification/status' => 'on',
          'notification/email' => ''
      );
      public static function init(){
            if (isset($_POST['bug-monitor-settings'])){
                  add_action('admin_init', array(__CLASS__, 'save_settings'));
            }
            add_action('init', array(__CLASS__, 'init_db'));

            if (isset($_GET['swte-connect']) && preg_match('~bug-?monitor~', $_GET['swte-connect'])){
                  add_action('admin_init', function(){
                        if (current_user_can('manage_options') && !defined('DOING_AJAX')){
                              Bug_Monitor::update_option('activated',1);
                              Bug_Monitor::update_option('api-error', false);

                              if (isset($_GET['mhp-license'])){
                                    Bug_Monitor::update_option('license-handling','v2');
                              }
                              else {
                                    Bug_Monitor::update_option('license-handling','v1');
                              }

                              wp_redirect(Bug_Monitor_Helper::get_dashbord_url());
                              die;
                        }
                  });
            }
            if (!defined('WP_UNINSTALL_PLUGIN') && is_admin()){
                  add_filter('site_transient_update_plugins', array(__CLASS__, 'update'));
                  add_filter('plugins_api', array(__CLASS__, 'plugin_data'), 10, 3);
            }
            if (isset($_GET['bug-monitor-check-for-updates'])){
                  add_action('admin_init', function(){
                        wp_cache_delete('update_plugins', 'site-transient');
                        delete_transient('bug_monitor_update_data');
                        wp_update_plugins();
                  });
            }
            add_action('bug_monitor/option_updated', array(__CLASS__, 'sync_settings'), 10, 2);
      }

      public static function get_options(){
            $options = get_option('bug_monitor_options', array());
            if (empty($options)){
                  $options = apply_filters('bug_monitor/save-settings', self::$settings);
                  update_option('bug_monitor_options', (array)$options);
            }
            if (empty($options['notification/setup'])){
                  $remove_legacy = false;
                  if (!empty($options['notification/email'])){
                        $remove_legacy = true;
                        $email = $options['notification/email'];
                  }
                  else {
                        $email = get_bloginfo('admin_email');
                  }
                  $data = json_encode(array(
                        'label' => $email,
                        'email' => $email
                  ));
                  $res = Bug_Monitor_API::request('notifications', array('action' => 'put', 'type' => 'email', 'data' => $data));
                  if (!empty($res)){
                        $options['notification/setup'] = 1;
                        if ($remove_legacy){
                              unset($options['notification/email']);
                        }

                        update_option('bug_monitor_options', (array)$options);
                  }
            }

            return $options;
      }

      public function save_settings(){
            if (wp_verify_nonce($_POST['bug-monitor-settings'], 'bug-monitor-settings') && current_user_can('manage_options')){
                  $settings = apply_filters('bug_monitor/save-settings', self::$settings);

                  foreach($settings as $key => $value){
                        $value = (isset($_POST[$key]) ? $_POST[$key] : '');
                        Bug_Monitor::update_option($key, $value);
                  }
            }
      }

      public static function init_db(){
            if (!self::is_db_uptodate()){
                  $hits = "CREATE TABLE " . Bug_Monitor_Helper::$db->bug_monitor_hits . " (
                        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                        URL VARCHAR(255) NOT NULL,
                        wfe INT(11) NOT NULL,
                        hit INT(11) NOT NULL,
                        bounce INT(11) NOT NULL,
                        PRIMARY KEY (id),
                        UNIQUE KEY URL (URL),
                        KEY bounce (URL)
                  );";

                  $events = "CREATE TABLE " . Bug_Monitor_Helper::$db->bug_monitor_events . " (
                        ID VARCHAR(32) NOT NULL,
                        event_hash VARCHAR(32) NOT NULL,
                        session_hash VARCHAR(32) NOT NULL,
                        screenshot_hash VARCHAR(32) NOT NULL,
                        level VARCHAR(50) NOT NULL,
                        type VARCHAR(50) NOT NULL,
                        URL VARCHAR(255) NOT NULL,
                        details TEXT NOT NULL,
                        ua TEXT NOT NULL,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        status INT(11) NOT NULL,
                        encrypted INT(1) NOT NULL,
                        PRIMARY KEY (ID),
                        KEY event_hash (event_hash),
                        KEY level (level),
                        KEY type (type),
                        KEY URL (URL),
                        KEY timestamp (timestamp),
                        KEY status (status),
                        KEY encrypted (encrypted)
                  );";

                  $sessions = "CREATE TABLE " . Bug_Monitor_Helper::$db->bug_monitor_sessions . " (
                        hash VARCHAR(32) NOT NULL,
                        ua VARCHAR(255) NOT NULL,
                        resolution VARCHAR(50) NOT NULL,
                        source MEDIUMTEXT NOT NULL,
                        preview MEDIUMTEXT NOT NULL,
                        mutations MEDIUMTEXT NOT NULL,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        encrypted INT(1) NOT NULL,
                        PRIMARY KEY hash (hash),
                        KEY resolution (resolution),
                        KEY ua (ua),
                        KEY timestamp (timestamp),
                        KEY encrypted (encrypted)
                  );";

                  $screenshots = "CREATE TABLE " . Bug_Monitor_Helper::$db->bug_monitor_screenshots . " (
                        hash VARCHAR(32) NOT NULL,
                        source MEDIUMTEXT NOT NULL,
                        preview MEDIUMTEXT NOT NULL,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        encrypted INT(1) NOT NULL,
                        PRIMARY KEY hash (hash),
                        KEY timestamp (timestamp),
                        KEY encrypted (encrypted)
                  );";

                  require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
                  dbDelta($hits);
                  dbDelta($events);
                  dbDelta($sessions);
                  dbDelta($screenshots);

                  Bug_Monitor::update_option('db_version', self::$db_version);
            }

      }

      public static function is_db_uptodate(){
            return Bug_Monitor::check_option('db_version', self::$db_version);
      }
      public static function install_mu_loader(){
            $mu_loader_path = WP_CONTENT_DIR . '/mu-plugins/__bug-monitor-loader.php';
            if (!file_exists(WP_CONTENT_DIR . '/mu-plugins')){
                  if (is_writeable(WP_CONTENT_DIR)){
                        @mkdir(WP_CONTENT_DIR . '/mu-plugins', 0755);
                  }
            }
            $mu_loader = file_get_contents(BUG_MONITOR_PLUGIN_DIR . 'templates/mu-loader.tpl.php');
            $mu_loader = str_replace(array('%PLUGIN_HEADER%', '%PLUGIN_DIR%', '%PLUGIN_BASENAME%'), array('Plugin Name: BugMonitor Loader', BUG_MONITOR_PLUGIN_DIR, BUG_MONITOR_PLUGIN_SLUG), $mu_loader);
            file_put_contents($mu_loader_path, $mu_loader);

      }
      public static function uninstall_mu_loader(){
            $mu_loader_path = WP_CONTENT_DIR . '/mu-plugins/__bug-monitor-loader.php';
            if (file_exists($mu_loader_path)){
                  unlink($mu_loader_path);
            }
      }
      public static function update($transient){
            $update_data = get_transient('bug_monitor_update_data');

            if (empty($update_data)){
                  $update_info = Bug_Monitor_Api::request('update/info');
                  if (empty($update_info)){
                        return $transient;
                  }

                  $update_data = json_decode($update_info['body']);
                  set_transient('bug_monitor_update_data', $update_data, 3600);
            }

            $plugin_data = get_plugin_data(BUG_MONITOR_PLUGIN_FILE);

            if ( ! is_object( $transient ) ) {
			$transient = new \stdClass();
		}

            if (!empty($update_data) && is_object($update_data) && version_compare($plugin_data['Version'], $update_data->version, '<')) {
                  $plugin_base = plugin_basename(BUG_MONITOR_PLUGIN_FILE);

                  $obj = new stdClass();
                  $obj->slug = 'bug-monitor';
                  $obj->new_version = $update_data->version;
                  $obj->url = $update_data->homepage;
                  $obj->package = $update_data->download_url;
                  $obj->sections = array(
                        'description' => $update_data->sections->description,
                        'changelog' => $update_data->sections->changelog
                  );
                  $transient->response[$plugin_base] = $obj;
            }

            return $transient;
      }

      public static function plugin_data ($res, $action, $args) {
            if ($action === 'plugin_information' && $args->slug === 'bug-monitor') {
                  $transient = self::update(null);
                  $plugin_base = plugin_basename(BUG_MONITOR_PLUGIN_FILE);
                  $data = $transient->response[$plugin_base];
                  $response = $data;
                  $response->name = 'BugMonitor';
                  $response->author = 'SWTE Plugins';
                  $response->download_link = $data->package;

                  $response->banners = array(
                        'low' => 'https://bug-monitor.com/images/banner-low.jpg',
                        'high' => 'https://bug-monitor.com/images/banner.jpg'
                  );
                  $response->icons = array(
                        'default' => 'https://bug-monitor.com/images//icon.png',
                  );

                  return $response;
            }

            return $res;
      }

      public static function sync_settings($value, $key){
            if ($key == 'server/uptime'){
                  Bug_Monitor_Api::request('uptime', array('enabled' => $value));
            }
      }

}

Bug_Monitor_Config::init();

 ?>