<?php

namespace RtmMail\Actions\Handlers;

use RtmMail\Helpers\LogHelper;
use RtmMail\Logger;
use RtmMail\Utils\LoggerUtils;
use WP_User;

class EditLogAction extends AbstractActionHandler
{
    public function __construct()
    {
        parent::__construct('edit', 'rtm_mail_edit_log');
    }

    public function handleAction(
        $logId = null,
        $subject = '',
        $senderOptions = [ 'title' => '', 'address' => '' ],
        $receiver = '',
        $cc = '',
        $bcc = '',
        $body = ''
    ): array {
        if (! $this->verifyNonce()) {
            return [ 'success' => false, 'message' => 'Nonce verification failed.' ];
        }

        $mail_log = LogHelper::get([
            'post_per_page' => null,
            'where'         => [ 'id' => [ 'type' => '=', 'value' => $logId ] ]
        ]);

        if (! isset($mail_log[0])) {
            return [ 'success' => false, 'message' => 'Log not found.' ];
        }

        // Processing sender options
        $sender_title   = ! empty($senderOptions['title']) ? $senderOptions['title'] : get_bloginfo('name');
        $sender_address = ! empty($senderOptions['address']) ? $senderOptions['address'] : get_option('admin_email');
        if (count(explode('<', $sender_address)) > 1) {
            list( $sender_title, $new_address ) = explode('<', $sender_address);
            $sender_title   = rtrim($sender_title, ' ');
            $sender_address = rtrim($new_address, '>');
        }
        $headers = array_merge($mail_log[0]["headers"], [ 'from' => $sender_title . ' <' . $sender_address . '>' ]);

        // Processing receiver details
        $receivers       = explode(';', str_replace(',', ';', $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']);

        // Updating the log
        LogHelper::update($logId, [
            'subject'         => $subject,
            'sender'          => $sender_address,
            'receiver'        => json_encode($receivers),
            'cc'              => json_encode(explode(';', str_replace(',', ';', $cc))),
            'bcc'             => json_encode(explode(';', str_replace(',', ';', $bcc))),
            'headers'         => json_encode($headers),
            'body'            => stripslashes(htmlspecialchars_decode($body)),
            'updated'         => date('Y-m-d H:i:s'),
            'receiver_status' => json_encode($receiver_status),
        ]);

        // Logging the edit
        $user_data = get_user_by('id', get_current_user_id());
        Logger::info(
            "Edited log #{$logId}",
            "{$user_data->display_name} edited Email Log: #{$logId}",
            'Details::handle_requests',
            'Log',
            [
                "mail_log" => $logId,
                "user"     => LoggerUtils::getUser(),
            ]
        );

        return [
            'success'  => true,
            'message'  => 'Log edited successfully.',
            'redirect' => get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $logId . '&edit_successful=true'
        ];
    }
}
