<?php

namespace RtmMail\Actions\Handlers;

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

class DeleteMultipleLogsAction extends AbstractActionHandler
{
    public function __construct()
    {
        parent::__construct('delete_log_rows', 'rtm_mail_delete_log_rows');
    }

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

        // Retrieve the IDs
        foreach ($log_ids as $id) {
            if (!empty($id)) {
                LogHelper::delete(['id' => $id]);

                // Get the current user's data
                $user_data = get_user_by('id', get_current_user_id());

                // Log a warning message for the deleted log
                Logger::warning(
                    "Deleted log #{$id}",
                    "Email Log (#{$id}) has been deleted by {$user_data->display_name}",
                    'Overview::handle_requests',
                    'Log',
                    [
                        "mail_log" => $id,
                        "user"     => LoggerUtils::getUser(),
                    ]
                );
                wp_clear_scheduled_hook('rtm_mail_send_log', [ $id ]);
            }
        }

        return [ 'success' => true, 'message' => __('Row(s) successfully deleted', 'rtm-mail') ];
    }
}
