<?php

namespace SEOAIC\traits;

use Exception;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SEOAICAjaxResponse;

trait MassActionsWorkflow
{
    public function postsMassActionRun($instance, $data = [], $sendResponse = true)
    {
        try {
            $data = !empty($data) ? $data : $instance->prepareData($_REQUEST);
            $result = $instance->sendActionRequest($data);

            if ($instance->processActionResults($result)) {
                $errors = $instance->getErrors();

                if (empty($errors)) {
                    if (!$sendResponse) {
                        return;
                    }

                    if ($instance->isAPI) {
                        return Result::success(__FUNCTION__, $instance->successfullRunMessage, []);
                    } else {
                        SEOAICAjaxResponse::success($instance->successfullRunMessage)->wpSend();
                    }

                } else {
                    if ($instance->isAPI) {
                        return Result::error(__FUNCTION__, "Run with some errors: ".$errors, []);
                    } else {
                        SEOAICAjaxResponse::alert("Run with some errors:<br>".$errors)->wpSend();
                    }
                }
            }
        } catch (Exception $e) {
            if ($instance->isAPI) {
                return Result::error(__FUNCTION__, $e->getMessage());
            } else {
                SEOAICAjaxResponse::error($e->getMessage())->wpSend();
            }
        }

        // other cases
        if ($sendResponse) {
            if ($instance->isAPI) {
                return Result::error(__FUNCTION__, 'Something went wrong');
            } else {
                SEOAICAjaxResponse::error('Something went wrong')->wpSend();
            }
        }
    }

    public function postsMassActionCheckStatusData($instance)
    {
        list('done' => $done, 'failed' => $failed, 'is_running' => $isRunning) = $instance->getStatusResults();
        $status = $isRunning ? 'in progress' : 'complete';
        $message = $isRunning ? '' : $instance->completeMessage;

        return [
            'message' => $message,
            'data' => [
                'status'    => $status,
                'done'      => $done,
                'failed'    => $failed,
            ],
        ];
    }

    public function postsMassActionCheckStatus($instance)
    {
        $data = $this->postsMassActionCheckStatusData($instance);

        SEOAICAjaxResponse::success($data['message'])->addFields($data['data'])->wpSend();
    }

    public function postsMassActionStop($instance, $sendMessage = true)
    {
        $instance->stop();

        if ($sendMessage) {
            SEOAICAjaxResponse::alert($instance->stopMessage)->wpSend();
        }
    }
}
