<?php

namespace RtmMail\Actions\Handlers;

use RtmMail\CustomMailer;

class SendMultipleLogsAction extends AbstractActionHandler
{
    public function __construct()
    {
        parent::__construct('send_log_rows', 'rtm_mail_send_log_rows');
    }

    /**
     * Handles the action of sending one or more logs. If a single log ID is given, it is converted to an array.
     *
     * @param mixed $logIds Either an array of log IDs or a single log ID.
     * @return array The result of the log sending operation.
     */
    public function handleAction($logIds = []): array
    {
        if (!is_array($logIds)) {
            $logIds = [$logIds];  // Convert single log ID to an array
        }

        if (! $this->verifyNonce()) {
            return [ 'success' => false, 'message' => 'Nonce verification failed.' ];
        }

        if (empty($logIds)) {
            return ['success' => false, 'message' => 'No logs selected.'];
        }

        $errors = [];
        foreach ($logIds as $id) {
            if (!empty($id)) {
                $mail_sent = CustomMailer::sendMail($id);
                wp_clear_scheduled_hook('rtm_mail_send_log', [$id]);
                if ($mail_sent !== 'success') {
                    $errors[] = sprintf(__('Error sending email log: #%1$s (%2$s)', 'rtm-mail'), $id, $mail_sent);
                }
            }
        }
        if (!empty($errors)) {
            return ['success' => false, 'message' => implode("\n", $errors)];
        }

        return ['success' => true, 'message' => __('Selected row(s) were sent', 'rtm-mail')];
    }
}
