<?php

namespace App\Services\Forms\Applications;

use App\Models\Applications\Application;
use App\Models\Applications\Conclusion;
use App\Models\Objects\FieldType;
use App\Services\Forms\FormsService;
use App\Transformers\Applications\ConclusionTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class ConclusionForms extends FormsService {
    public array $formTitles = ['create' => 'Ответ на заявку', 'update' => 'Редактирование ответа'];

    public function form(?string $id = null, array $data = []): array {
        $model = Conclusion::byUuid($id)->first();
        return [
            'title' => $this->formTitle($model),
            'frames' => [
                ['title' => 'Общие сведения', 'groups' => $this->form1Groups($model)],
            ]
        ];
    }

    public function form1Groups(?Conclusion $model): array {
        $groups = [
            ['name' => 'common', 'title' => '', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['data' => $groups];
    }

    public function commonGroupFields(?Conclusion $model): array {
        $fields = [
            [
                'name' => 'message',
                'title' => 'Мнение эксперта',
                'type' => FieldType::HTML,
                'required' => true,
                'value' => $model->message ?? null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        $application = Application::byUuid($data['application'] ?? null)->firstOrFail();
        $model = $application->conclusions()->create(['author_id' => Auth::user()->id, 'message' => $data['message'] ?? null]);
        $application->complete();
        return fractal($model, new ConclusionTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Conclusion::byUuid($id)->firstOrFail();
        $model->update(['message' => $data['message'] ?? null]);
        return fractal($model, new ConclusionTransformer())->respond();
    }

}
