<?php

class Bug_Monitor_Notification {

      public static function instant($subject, $message){
            $email = Bug_Monitor::get_option('notification/email');
            $body = Bug_Monitor_Helper::get_template('email/instant', array('message' => $message, 'title' => $subject));
            $result = Bug_Monitor_API::request('notification', array(
                  'email' => (empty($email) ? get_bloginfo('admin_email') : $email),
                  'subject' => $subject,
                  'body' => $body
            ));
      }

      public static function five_minutes_notifications(){
            $logs = Bug_Monitor_Log::get_logs(array('status' => 1, 'level' => 'critical'));
            $count = count($logs);
            if ($count > 0){
                  $mail_body = Bug_Monitor_Helper::get_template('email/summary', array('logs' => $logs, 'title' => _n('Critical error occurred', 'Critical errors occurred', $count, 'bug-monitor'), 'description' => sprintf(_n('%d critical error occurred on %s', '%d critical errors occurred on %s', $count, 'bug-monitor'), $count, home_url())));
                  $events = self::prepare_notification_events($logs);
                  $result = Bug_Monitor_API::request('notifications', array(
                        'action' => 'send',
                        'subject' => sprintf(_n('Critical Error occured on %s', 'Critical Errors occured on %s', $count, 'bug-monitor'), home_url()),
                        'mail_body' => $mail_body,
                        'dashboard_url' => Bug_Monitor_Helper::get_dashbord_url(),
                        'events' => $events
                  ));
                  if (!empty($result)){
                        self::update_status($logs);
                  }
            }
      }

      public static function daily_notifications(){
            $logs = Bug_Monitor_Log::get_logs(array('status' => 1, 'level' => array('error', 'warning')));
            $count = count($logs);
            if ($count > 0){
                  $body = Bug_Monitor_Helper::get_template('email/summary', array('logs' => $logs, 'title' => __('Summary', 'bug-monitor'), 'description' => sprintf(_n('This summary includes errors and warnings. We send instant notifications about critical errors. %d event has been reported on %s', 'This summary includes errors and warnings. We send instant notifications about critical errors. %d events has been reported on %s', $count, 'bug-monitor'), $count, home_url())));
                  $result = Bug_Monitor_API::request('notifications', array(
                        'action' => 'summary',
                        'subject' => sprintf(__('Summary - %s', 'bug-monitor'), home_url()),
                        'body' => $body
                  ));
                  if (!empty($result)){
                        self::update_status($logs);
                  }
            }
      }

      public static function prepare_notification_events($logs){
            $events = array();

            foreach ($logs as $key => $data){
                  $events[$key] = array(
                        'category' => $data['category'],
                        'level' => $data['level'],
                        'title' => Bug_Monitor_Dashboard::get_title($data['type']),
                        'category_label' => Bug_Monitor_Dashboard::get_category($data['category']),
                        'level_label' => Bug_Monitor_Dashboard::get_level($data['level']),
                        'timestamps' => Bug_Monitor_Dashboard::get_timestamps($data),
                        'count' => $data['count'],
                        'desc' => Bug_Monitor_Dashboard::get_description($data)
                  );
            }

            return $events;
      }

      public static function update_status($logs){
            $event_hashes = array();
            foreach ($logs as $key => $value) {
                  $event_hashes[] = $key;
            }

            Bug_Monitor_Helper::$db->query("UPDATE " . Bug_Monitor_Helper::$db->bug_monitor_events . " SET status = 2 WHERE event_hash IN(" . implode(',', array_map(function($e){
                  return '"' . $e . '"';
            }, $event_hashes)) . ")");
      }

      public static function check_endpoints(){
            $res = Bug_Monitor_API::request('notifications', array('action' => 'check'));
            if (!empty($res['body'])){
                  $response = json_decode($res['body']);
                  if ($response->valid < 1){
                        Bug_Monitor_Dashboard::add_notice(sprintf(__('There is no valid notification endpoint set. Please %sadd a valid e-mail, push or webhook endpoint%s to receive notifications.', 'bug-monitor'), '<a href="' . Bug_Monitor_Helper::get_dashbord_url() . '#settings/notifications">', '</a>'));
                  }
                  if (!empty($response->errors)){
                        foreach ($response->errors as $key => $value){
                              Bug_Monitor_Dashboard::add_notice(sprintf(__('E-mail bounced for %s%s%s. Error: %s', 'bug-monitor'), '<strong>', $key, '</strong>', esc_html($value)), $key);
                        }
                  }
            }
      }

}