<?php

namespace Mtc\Plugins\MtcUnioIntegration\Http\Controllers\Api;

use Illuminate\Http\Request;
use Mtc\Plugins\MtcUnioIntegration\Classes\QueueMessageFromUnio;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Routing\Controller as BaseController;


class QueueFromUnioController extends BaseController
{

    public function messages(Request $request)
    {
        $result = [
            'errors' => [],
            'data' => null,
        ];

        $payload_string = $request->getContent();
        $payload_array = json_decode($payload_string, true);

        $message = new QueueMessageFromUnio();
        $message->payload_received = $payload_string;

        if ($payload_array && is_array($payload_array)) {

            $message->entity_type = $payload_array['entity_type'];
            $message->entity_id = $payload_array['entity_id'];

            $errors_bag = $message->validate()->errors();
            if ($errors_bag->isEmpty()) {
                try {
                    $message->save();
                } catch (\Exception $e) {
                    $result['errors']['server'] = "Message couldn't be saved.";
                }
            } else {
                $result['errors'] += \App\FlashMessage::getImplodedMessages($errors_bag);
            }

        } else {
            $result['errors']['payload'] = "Invalid JSON provided.";
        }

        $result['data'] = $message;

        return response()->json($result);
    }

}

