<?php

defined('ABSPATH') or exit('Hey, what are you doing here? You silly human!');

if (! class_exists('Dusky_Cron')) {
    class Dusky_Cron
    {
        private static $instance = null;

        public function __construct()
        {
            add_filter('cron_schedules', [$this, 'dusky_every_month_schedule']);
            add_action('dusky_schedule_event', [$this, 'dusky_schedule_reporting']);

            $this->schedule_start();
            $this->schedule_end();
        }

        public function dusky_every_month_schedule($schedules)
        {

            $schedules['monthly'] = [
                'interval' => 60 * 60 * 24 * 30,
                'display'  => __('Once Monthly', 'dusky-dark-mode'),
            ];

            return $schedules;
        }

        private function schedule_start()
        {

            $isActive = dusky_get_settings('emailReporting', false);

            if ($isActive) {
                $this->dusky_cron_activate();
            }

        }
        private function schedule_end()
        {

            $isActive = dusky_get_settings('emailReporting', false);

            if (! $isActive) {
                $this->dusky_cron_deactivate();
            }
        }

        public function dusky_schedule_reporting()
        {
            Dusky_Mail::send();
            add_option('dusky_reporting_email_start_at', gmdate('Y-m-d H:i:s', time()));
        }

        private function validateArrayIndex($array, $key, $default = '')
        {
            return $array[$key] ?? $default;
        }

        private function dusky_cron_activate()
        {
            $dusky_get_settings = dusky_get_settings();

            $settings = [
                'frequency' => $this->validateArrayIndex($dusky_get_settings, 'reportingFrequency', 'weekly'),
                'sendTime'  => $this->validateArrayIndex($dusky_get_settings, 'emailSendTime', '09:00:00'),
                'timeZone'  => $this->validateArrayIndex($dusky_get_settings, 'timeZone', 'UTC'),
            ];

            $default_schedule_settings = [
                'frequency' => 'weekly',
                'sendTime'  => '09:00:00',
                'timeZone'  => 'UTC',
            ];

            $dusky_current_frequency = get_option('default_schedule_settings', $default_schedule_settings);

            if ($dusky_current_frequency !== $settings) {
                $this->dusky_cron_deactivate();
            }

            if (! wp_next_scheduled('dusky_schedule_event')) {
                wp_schedule_event($this->get_timestamp(), $settings['frequency'], 'dusky_schedule_event');
                update_option('default_schedule_settings', $settings);
            }
        }

        private function dusky_cron_deactivate()
        {
            wp_clear_scheduled_hook('dusky_schedule_event');
        }

        private function get_timestamp()
        {
            $time_zone = dusky_get_settings('timeZone', null);
            $desired_time = dusky_get_settings('emailSendTime', '09:00:00');

            $wp_timezone = new DateTimeZone($time_zone) ?: wp_timezone();

            $current_date = date_create('now', $wp_timezone)->format('Y-m-d');

            $date_timeString = "$current_date $desired_time";

            return strtotime($date_timeString, current_time('timestamp', true));
        }

        public static function instance()
        {
            if (self::$instance === null) {
                self::$instance = new self();
            }

            return self::$instance;
        }
    }

}

Dusky_Cron::instance();
