<?php

namespace RtmMail\Actions\Handlers;

use RtmMail\Catcher;
use RtmMail\CustomMailer;

class SendLogAction extends AbstractActionHandler
{
    public function __construct()
    {
        parent::__construct('send_log', 'rtm_mail_send_log');
    }

    public function handleAction($logId = 0): array
    {
        // Verify nonce
        if (!$this->verifyNonce()) {
            return ['success' => false, 'message' => 'Nonce verification failed.'];
        }

        // Check required parameter
        if (empty($logId)) {
            return ['success' => false, 'message' => 'Log ID is required.'];
        }

        // Attempt to send the log
        $mail_sent = CustomMailer::sendMail($logId);
        wp_clear_scheduled_hook('rtm_mail_send_log', [$logId]);

        // Determine response based on the result of sending the mail
        if ($mail_sent === 'success') {
            return [
                'success' => true,
                'message' => 'Email successfully sent.',
                'redirect' => get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $logId . '&sent_successful=true'
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Failed to send email.',
                'redirect' => get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $logId . '&sent_failed=' . $mail_sent
            ];
        }
    }
}
