<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Exit if accessed directly
}


class ISTKR_Notificator
{
    public $action;
    public $options;
    public $email_recurrences;
    public $send_test_email_handler;

    public function __construct($instance) {
        $istkr_404_controller = new ISTKR_404Controller();
        $istkr_advisor_controller = new ISTKR_AdvisorController();
        $istkr_log_controller = new ISTKR_LogController();

        if ($instance instanceof $istkr_404_controller) {
            $this->action = ISTKR_404Controller::SCHEDULE_MAIL_SEND;
            $this->send_test_email_handler = [$this, 'istkr_send_404_test_email'];
        } elseif ($instance instanceof $istkr_advisor_controller) {
            $this->action = ISTKR_AdvisorController::SCHEDULE_MAIL_SEND;
            $this->send_test_email_handler = [$this, 'istkr_send_advisor_test_email'];
        } elseif ($instance instanceof $istkr_log_controller) {
            $this->action = ISTKR_LogController::SCHEDULE_MAIL_SEND;
            $this->send_test_email_handler = [$this, 'istkr_send_log_viewer_test_email'];
        }
        $this->email_recurrences = [
            'hourly'     => __('Hourly', 'istkr'),
            'twicedaily' => __('Twice Daily', 'istkr'),
            'daily'      => __('Daily',  'istkr'),
            'weekly'     => __('Weekly', 'istkr'),
        ];
        $this->options = get_option($this->istkr_build_unique_event_name());
    }

    public function istkr_build_unique_event_name()
    {
        return strtoupper($this->action . '_user_' . wp_get_current_user()->ID);
    }

    public function istkr_get_notification_email()
    {
        if ($this->options && array_key_exists('notifications_email', $this->options)) {
            return $this->options['notifications_email'];
        }
    }

    public function istkr_is_notification_enabled()
    {
        return (bool) $this->options;
    }

    public function istkr_get_notification_recurrence()
    {
        $html_options = '';
        foreach ($this->email_recurrences as $key => $value) {
            $selected = $key == $this->istkr_get_notification_recurrences() ? 'selected="selected"' : '';
            $html_options .= sprintf('<option value="%s" %s>%s</option>', $key, $selected, $value);
        }
        return $html_options;
    }

    private function istkr_get_notification_recurrences()
    {
        if (!$this->options) {
            return null;
        }

        if (array_key_exists('notifications_email_recurrence', $this->options)) {
            return $this->options['notifications_email_recurrence'];
        }
        return null;
    }

    private function istkr_send_log_viewer_test_email($args)
    {
        global $ISTKR_LOG_VIEWER_EMAIL_LEVELS;

        $email = $args['notifications_email'];

        if (!isset($email)) {
            return;
        }

        $errors = [];
        foreach ($ISTKR_LOG_VIEWER_EMAIL_LEVELS as $type) {
            $timestamp = new DateTime();
            $datetime = $timestamp->format('Y-m-d H:i:s e');
            $text = $type . ' error test description';
            $hash = md5($text . '::' . $datetime);

            $errors[$type][$hash] = [
                'datetime'    => $datetime,
                'line'        => '1',
                'file'        => 'example.php',
                'type'        => $type,
                'description' => [
                    'text' => $text,
                    'stack_trace' => null,
                ],
                'hits' => 1,
            ];
        }

        istkr_send_log_viewer_email(
            $email,
            __('Issues Tracker: Log monitoring test email'),
            realpath(__DIR__) . '/../templates/email/log_viewer.tpl',
            [
                'website' => get_site_url(),
                'errors' => $errors,
            ]
        );
    }

    private function istkr_send_advisor_test_email($args)
    {
        global $WP_CRON_SCHEDULE_INTERVALS;
        
        $email = $args['notifications_email'];

        if (!isset($email)) {
            return;
        }

        $summary = '' .
            '<tr>' .
            '   <td>Problem</td>' .
            '    <td>Solution</td>' .
            '</tr>' .
            '<tr>' .
            '    <td>Problem description</td>' .
            '    <td>Problem solution</td>' .
            '</tr>';

        $recurrence = $args['notifications_email_recurrence'];
        $datetime = new DateTime();
        $datetime->sub($WP_CRON_SCHEDULE_INTERVALS[$recurrence]);
        $next_check = $datetime->format('Y-m-d H:i:s');

        istkr_send_advisor_email(
            $email,
            __('Issues Tracker: Advisor monitoring test email'),
            realpath(__DIR__) . '/../templates/email/advisor.tpl',
            [
                'website' => get_site_url(),
                'summary' => $summary,
                'next_check' => $next_check,
                'change_recurrence' => admin_url() . 'admin.php?page=issues-tracker-advisor',
            ]
        );
    }

    private function istkr_send_404_test_email($args)
    {
        $email = $args['notifications_email'];

        if (!isset($email)) {
            return;
        }

        $timestamp = new DateTime();

        $records = [
            [
                'path' => '/some-resource.php',
                'updated_at' => $timestamp->format('Y-m-d H:i:s'),
                'ip' => '0.0.0.0',
                'country_name' => 'Country',
                'country_flag' => null,
                'referrer' => '	N/A',
            ]
        ];
        
        istkr_send_404_email(
            $email,
            __('Issues Tracker: 404 monitoring test email'),
            realpath(__DIR__) . '/../templates/email/404.tpl',
            [
                'website' => get_site_url(),
                'records' => $records,
            ]
        );
    }

    public function istkr_send_test_email($options)
    {
        if (isset($this->send_test_email_handler) && is_callable($this->send_test_email_handler)) {
            call_user_func($this->send_test_email_handler, $options);
        }
    }
}
