<?php

namespace App\Services\Forms\Applications;

use App\Models\Applications\Application;
use App\Models\Applications\ApplicationStatus;
use App\Models\Objects\FieldType;
use App\Models\Products\Product;
use App\Services\Forms\FormsService;
use App\Transformers\Applications\ApplicationTransformer;
use App\Transformers\Assets\AssetTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

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

    public function form(?string $id = null, array $data = []): array {
        $model = Application::byUuid($id)->first();
        return [
            'title' => $this->formTitle($model),
            'frames' => [
                ['title' => 'Общие сведения', 'groups' => $this->form1Groups($model)],
                ['title' => 'Документация', 'groups' => $this->form2Groups($model)]
            ]
        ];
    }

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

    public function form2Groups(?Application $model): array {
        $groups = [
            ['name' => 'documents', 'title' => '', 'fields' => $this->documentsGroupFields($model)]
        ];
        return ['data' => $groups];
    }

    public function commonGroupFields(?Application $model): array {
        $fields = [
            [
                'name' => 'applicant',
                'title' => 'Организация-заявитель',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->applicant ?? null
            ],
            [
                'name' => 'product_name',
                'title' => 'Hаименование продукции',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->product->name ?? null
            ],
            [
                'name' => 'product_purpose',
                'title' => 'Hазначение продукции',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->product->purpose ?? null
            ],
            [
                'name' => 'product_usage',
                'title' => 'Область применения продукции',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->product->usage ?? null
            ],
            [
                'name' => 'normative',
                'title' => 'Нормативно-технический документ',
                'type' => FieldType::STRING,
                'value' => $model->product->normative ?? null
            ],
            [
                'name' => 'producer',
                'title' => 'Изготовитель/разработчик',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->product->producer ?? null
            ]
        ];
        return ['data' => $fields];
    }

    public function documentsGroupFields(?Application $model): array {
        $fields = [
            [
                'name' => 'documents',
                'title' => 'Документация',
                'type' => FieldType::DOCUMENT,
                'multiple' => true,
                'value' => $model ? fractal($model->properties->getValue('documents'), new AssetTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        $product = Product::create();
        $model = Application::create(['submitter_id' => Auth::user()->id, 'product_id' => $product->id, 'number' => Application::generateNumber(), 'status' => ApplicationStatus::PROCESSING]);
        $this->updateData($model, $data);
        $model->submit();
        return fractal($model, new ApplicationTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Application::byUuid($id)->firstOrFail();
        $this->updateData($model, $data);
        return fractal($model, new ApplicationTransformer())->respond();
    }

    public function updateData(Application $model, array $data) {
        $model->update(['applicant' => $data['applicant'] ?? null]);
        $model->product->update(['name' => $data['product_name'] ?? null, 'purpose' => $data['product_purpose'] ?? null, 'usage' => $data['product_usage'] ?? null,
            'normative' => $data['normative'] ?? null, 'producer' => $data['producer'] ?? null]);
        $model->properties->setValue('documents', $data['documents'] ?? null);
    }

}
