<?php

namespace RtmMail;

use RtmMail\Helpers\LogHelper;

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

    /**
     * mail_log - single log object from the database
     * @var object
     */
    private $mail_log;

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

    /**
     * handle_requests - every page can handle their requests (post/get)
     */
    public function handle_requests()
    {
        // Check if user is on the details page
        if ($this->page_check()) {
            // If someone goes to the details page with a log_id
            if (isset($_GET['log_id'])) {
                // sanitize the log_id
                $log_id = sanitize_key($_GET['log_id']);
                // Get the log by the log_id and set it to the current log item
                $this->mail_log = LogHelper::get([
                    'post_per_page' => null,
                    'where' => [
                        'id' => [
                            'type' => '=',
                            'value' => $log_id,
                        ]
                    ]
                ]);
                // Check if the mail preview is requested
                if (isset($_GET['mail_preview']) && filter_var($_GET['mail_preview'], FILTER_VALIDATE_BOOLEAN)) {
                    global $log;
                    // set global $log to the current loaded log item
                    $log = $this->mail_log;
                    require_once __DIR__ . '/Views/preview.php';
                    // Don't render anymore
                    exit();
                }
            }

            // Show notification on successful edit
            if (isset($_GET['edit_successful'])) {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-success"> ';
                    echo '<p><strong>WP Mail Logger: </strong>';
                    echo __('Log successfully edited', 'rtm-mail');
                    echo '</p>';
                    echo '</div>';
                });
            }

            // Show notification on successful sent
            if (isset($_GET['sent_successful'])) {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-success"> ';
                    echo '<p><strong>WP Mail Logger: </strong>';
                    echo __('Email successfully sent', 'rtm-mail');
                    echo '</p>';
                    echo '</div>';
                });
            }

            // Show notification on failed sent
            if (isset($_GET['sent_failed'])) {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-error"> ';
                    echo '<p><strong>WP Mail Logger: </strong>';
                    echo $_GET['sent_failed'];
                    echo '</p>';
                    echo '</div>';
                });
            }

            // Check if an action is given
            if (isset($_POST['action'])) {
                // If the action is edit, check for the wp nonce
                if ($_POST['action'] === 'edit') {
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_edit_log')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            // Update every input
                            $mail_log = LogHelper::get([
                                'post_per_page' => null,
                                'where' => [
                                    'id' => [
                                        'type' => '=',
                                        'value' => $_POST['log_id'],
                                    ]
                                ]
                            ]);
                            if (isset($mail_log[0])) {
                                $sender_title = (!empty($_POST['sender_options']['title'])) ? $_POST['sender_options']['title'] : get_bloginfo('name');
                                $sender_address = (!empty($_POST['sender_options']['address'])) ? $_POST['sender_options']['address'] : get_option('admin_email');

                                $headers = array_merge($mail_log[0]["headers"], ['from' => $sender_title . ' <' . $sender_address . '>']);

                                $receivers = explode(';', str_replace(',', ';', $_POST['receiver']));
                                $receiver_status = [];
                                foreach ($receivers as $receiver_mail) {
                                    if (!empty($receiver_mail)) {
                                        $receiver_status[$receiver_mail] = [
                                            'opened' => (isset($mail_log[0]['receiver_status'][$receiver_mail]) && $mail_log[0]['receiver_status'][$receiver_mail]['opened']),
                                            'sent' => false,
                                        ];
                                    }
                                }
                                $receiver_status = array_merge($receiver_status, $mail_log[0]['receiver_status']);

                                LogHelper::update($_POST['log_id'], [
                                    'subject' => $_POST['subject'],
                                    'sender' => $sender_address,
                                    'receiver' => json_encode($receivers),
                                    'cc' => json_encode(explode(';', str_replace(',', ';', $_POST['cc']))),
                                    'bcc' => json_encode(explode(';', str_replace(',', ';', $_POST['bcc']))),
                                    'headers' => json_encode($headers),
                                    'body' => stripslashes(htmlspecialchars_decode($_POST['body'])),
                                    'updated' => date('Y-m-d H:i:s'),
                                    'receiver_status' => json_encode($receiver_status),
                                ]);
                            }
                            do_action('rtmmail_log_edited', $_POST['log_id'], get_current_user_id());
                            // redirect to the log details page
                            wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id'] . '&edit_successful=true');
                            exit();
                        }
                    }
                } else if ($_POST['action'] === 'send_log') {
                    // Verify wp nonce for sending email
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_send_log')) {
                        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']);
                                wp_clear_scheduled_hook('rtm_mail_send_log', [$_POST['log_id']]);
                                if ($mail_sent === 'success') {
                                    wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id'] . '&sent_successful=true');
                                } else {
                                    wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id'] . '&sent_failed=' . $mail_sent);
                                }
                                exit();
                            }
                        }
                    }
                } else if ($_POST['action'] === 'delete_log') {
                    // Verify wp nonce for deleting email
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_delete_log')) {
                        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());
                                wp_clear_scheduled_hook('rtm_mail_send_log', [$_POST['log_id']]);
                                // Redirect to overview
                                wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-overview&delete_successful=true');
                                // have to exit after redirect
                                exit();
                            }
                        }
                    }
                } else if ($_POST['action'] === 'remove_queue') {
                    // Verify wp nonce for deleting email
                    if (wp_verify_nonce($_POST['_wpnonce_remove_queue'], 'rtm_mail_remove_queue')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            if (isset($_POST['remove_log_queue'])) {
                                // Unschedule event
                                wp_unschedule_event($_POST['queue_timestamp'], 'rtm_mail_send_log', [$_POST['log_id']]);
                                // Update status
                                LogHelper::update($_POST['log_id'], ['status' => 'caught']);
                                // Create debug event
                                do_action('rtmmail_mail_queue_removed', $_POST['log_id']);
                                // Redirect to details
                                wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id']);
                                // have to exit after redirect
                                exit();
                            }
                        }
                    }
                } else if ($_POST['action'] === 'queue_log') {
                    // Verify wp nonce for deleting email
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_queue_mails')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            if (isset($_POST['queue-mail-log'])) {
                                $queue_timestamp = strtotime($_POST['queue_date'] . ' ' . wp_timezone_string());
                                if ($queue_timestamp > time()) {
                                    // Schedule by log_id
                                    wp_schedule_single_event($queue_timestamp, 'rtm_mail_send_log', [$_POST['log_id']]);
                                    // Update status to queued
                                    LogHelper::update($_POST['log_id'], ['status' => 'queued']);
                                    // Create debug event
                                    do_action('rtmmail_mail_queued', $_POST['log_id'], $_POST['queue_date']);
                                    // Redirect to details
                                    wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id']);
                                    exit();
                                } else {
                                    add_action('admin_notices', function () {
                                        echo '<div class="notice notice-error"> ';
                                        echo '<p><strong>WP Mail Logger: </strong>';
                                        echo __('Selected date and time are earlier then current time, please select a valid date and time!', 'rtm-mail');
                                        echo '</p>';
                                        echo '</div>';
                                    });
                                }
                            }
                        }
                    }
                } else if ($_POST['action'] === 'resend_mail') {
                    if (wp_verify_nonce($_POST['_wpnonce'], 'rtm_mail_resend_mail')) {
                        if (isset($_POST['log_id']) && !empty($_POST['log_id'])) {
                            if (isset($_POST['address']) && !empty($_POST['address'])) {
                                if (isset($_POST['resend-mail'])) {
                                    // Send the email with the given log id
                                    $mail_sent = Catcher::send_mail($_POST['log_id'], $_POST['address']);
                                    if ($mail_sent === 'success') {
                                        wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id'] . '&sent_successful=true');
                                    } else {
                                        wp_redirect(get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $_POST['log_id'] . '&sent_failed=' . $mail_sent);
                                    }
                                    exit();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * display - Displays the page view for the user
     */
    public function display()
    {
        // Check if user is on the details page
        if ($this->page_check()) {
            global $log;
            // set global $log to the current loaded log item
            $log = $this->mail_log;
            // load in the details view for the user
            require __DIR__ . '/Views/' . $this->slug . '.php';
        }
    }
}
