<?php

namespace RtmMail;

use Cassandra\Date;
use DateTime;
use RtmMail\Helpers\LogHelper;

/**
 * Overview - handles every user interaction for the overview page
 */
class Overview extends AbstractPage
{
    protected $slug = 'overview';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * handle_requests - every page can handle their requests (post/get)
     */
    public function handle_requests()
    {
        if ($this->page_check()) {

            if (isset($_POST['action'])) {
                if ($_POST['action'] === 'send_log') {
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_action_send')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            if (isset($_POST['send_log'])) {
                                // Send the email with the given log id
                                $mail_sent = Catcher::send_mail($_POST['log_id']);
                                // Unschedule queued log
                                wp_clear_scheduled_hook('rtm_mail_send_log', [$_POST['log_id']]);
                                if ($mail_sent === 'success') {
                                    // Display notification
                                    add_action('admin_notices', function () {
                                        echo '<div class="notice notice-success"> ';
                                        echo '<p><strong>WP Mail Logger: </strong>';
                                        echo __('Selected row was sent!', 'rtm-mail');
                                        echo '</p>';
                                        echo '</div>';
                                    });
                                } else {
                                    // Display error notification
                                    echo '<div class="notice notice-error"> ';
                                    echo '<p><strong>WP Mail Logger: </strong>';
                                    printf(__('Error sending email log: #%1$s (%2$s)', 'rtm-mail'), $_POST['log_id'], $mail_sent);
                                    echo '</p>';
                                    echo '</div>';
                                }
                            }
                        }
                    }
                } else if ($_POST['action'] === 'delete_log') {
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_action_delete')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            if (isset($_POST['delete_log'])) {
                                // Delete the log
                                LogHelper::delete(['id' => $_POST['log_id']]);
                                do_action('rtmmail_log_deleted', $_POST['log_id'], get_current_user_id());
                                // Redirect to overview
                                wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-overview&delete_successful=true');
                                exit();
                            }
                        }
                    }
                } else if ($_POST['action'] === 'test_mail') {
                    wp_mail(get_option('admin_email'), 'This is a sample subject', '<h1>This is a test</h1><p>This is just a test mail to see if everything is working OK</p>', 'Content-Type:text/html', []);
                    add_action('admin_notices', function () {
                        echo '<div class="notice notice-success"> ';
                        echo '<p><strong>WP Mail Logger: </strong>';
                        echo __('A test email was sent to the admin email!', 'rtm-mail');
                        echo '</p>';
                        echo '</div>';
                    });
                }
            }

            // Check if the user wants to delete logs
            if (isset($_GET['action'])) {
                if (isset($_GET['delete_log_rows'])) {
                    // Verify the delete nonce
                    if (wp_verify_nonce($_GET['_wpnonce_delete'], 'rtm_mail_delete_log_rows')) {
                        // Delete every selected id
                        if (isset($_GET['id'])) {
                            foreach ($_GET['id'] as $id) {
                                if (!empty($id)) {
                                    // delete by id
                                    LogHelper::delete(['id' => $id]);
                                    do_action('rtmmail_log_deleted', $id, get_current_user_id());
                                    // Unschedule queued log
                                    wp_clear_scheduled_hook('rtm_mail_send_log', [$id]);
                                }
                            }
                            // Display notification
                            add_action('admin_notices', function () {
                                echo '<div class="notice notice-success"> ';
                                echo '<p><strong>WP Mail Logger: </strong>';
                                echo __('Row(s) successfully deleted', 'rtm-mail');
                                echo '</p>';
                                echo '</div>';
                            });
                        }
                    }
                } else if (isset($_GET['send_log_rows'])) {
                    // Verify the sending nonce
                    if (wp_verify_nonce($_GET['_wpnonce_send'], 'rtm_mail_send_log_rows')) {
                        if (isset($_GET['id'])) {
                            foreach ($_GET['id'] as $id) {
                                if (!empty($id)) {
                                    $mail_sent = Catcher::send_mail($id);
                                    // Unschedule queued log
                                    wp_clear_scheduled_hook('rtm_mail_send_log', [$id]);
                                    if ($mail_sent != 'success') {
                                        // Display error notification
                                        echo '<div class="notice notice-error"> ';
                                        echo '<p><strong>WP Mail Logger: </strong>';
                                        printf(__('Error sending email log: #%1$s (%2$s)', 'rtm-mail'), $id, $mail_sent);
                                        echo '</p>';
                                        echo '</div>';
                                    }
                                }
                            }
                            // Display notification
                            add_action('admin_notices', function () {
                                echo '<div class="notice notice-success"> ';
                                echo '<p><strong>WP Mail Logger: </strong>';
                                echo __('Selected row(s) were sent', 'rtm-mail');
                                echo '</p>';
                                echo '</div>';
                            });
                        }
                    }
                } else if (isset($_GET['queue_logs'])) {
                    // verify queue nonce
                    if (wp_verify_nonce($_GET['_wpnonce_queue'], 'rtm_mail_queue_log')) {
                        // Get timestamp of selected date
                        $queue_timestamp = strtotime($_GET['queue_date'] . ' ' . wp_timezone_string());
                        if ($queue_timestamp > time()) {
                            if (isset($_GET['id'])) {
                                foreach ($_GET['id'] as $log_id) {
                                    // Schedule by log_id
                                    wp_schedule_single_event($queue_timestamp, 'rtm_mail_send_log', [$log_id]);
                                    // Update status to queued
                                    LogHelper::update($log_id, ['status' => 'queued']);
                                    // Create debug event
                                    do_action('rtmmail_mail_queued', $log_id, $_GET['queue_date']);
                                }
                                // Display notification
                                add_action('admin_notices', function () {
                                    echo '<div class="notice notice-success"> ';
                                    echo '<p><strong>WP Mail Logger: </strong>';
                                    echo __('Selected row(s) are queued', 'rtm-mail');
                                    echo '</p>';
                                    echo '</div>';
                                });
                            }
                        } else {
                            echo '<div class="notice notice-error"> ';
                            echo '<p><strong>WP Mail Logger: </strong>';
                            echo __('Error adding emails to queue: Timestamp is lower then current time, please choose a valid date and time!', 'rtm-mail');
                            echo '</p>';
                            echo '</div>';
                        }
                    }
                } else if (isset($_GET['dequeue_logs'])) {
                    // verify queue nonce
                    if (wp_verify_nonce($_GET['_wpnonce_dequeue'], 'rtm_mail_dequeue_log')) {
                        if (isset($_GET['id'])) {
                            foreach ($_GET['id'] as $log_id) {
                                // unschedule by log_id
                                wp_clear_scheduled_hook('rtm_mail_send_log', [$log_id]);
                                // Update status to queued
                                LogHelper::update($log_id, ['status' => 'caught']);
                                // Create debug event
                                do_action('rtmmail_mail_queue_removed', $log_id);
                            }
                            // Display notification
                            add_action('admin_notices', function () {
                                echo '<div class="notice notice-success"> ';
                                echo '<p><strong>WP Mail Logger: </strong>';
                                echo __('Selected row(s) are queued', 'rtm-mail');
                                echo '</p>';
                                echo '</div>';
                            });
                        }
                    }
                }
            } else if (isset($_GET['delete_successful'])) {
                // If deletion was successful display notification
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-success"> ';
                    echo '<p><strong>WP Mail Logger: </strong>';
                    echo __('Log successfully deleted', 'rtm-mail');
                    echo '</p>';
                    echo '</div>';
                });
            }
        }
    }
}