<?php

namespace App\Services\Forms\Publications;

use App\Models\Asset;
use App\Models\Objects\FieldType;
use App\Models\Pages\Page;
use App\Models\Publications\Publication;
use App\Models\Publications\PublicationType;
use App\Services\Forms\FormsService;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Publications\PublicationTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class PublicationPortfolioForms
    extends FormsService {
    public array $formTitles = ['create' => 'Создание новой публикации в портфолио', 'update' => 'Редактирование публикации в портфолио'];

    public function form(?string $id = null, array $data = []): array {
        $model = Publication::byUuid($id)->first();
        $groups = [
            ['name' => 'common', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['title' => $this->formTitle($model), 'data' => $groups];
    }

    public function commonGroupFields(?Publication $model): array {

        $params = $model->parsedParams ?? null;

        $fields = [
            [
                'name' => 'name',
                'title' => 'Название компании',
                'type' => FieldType::STRING,
                'required' => true,
                'max_length' => 127,
                'value' => $model->name ?? null
            ],
            [
                'name' => 'excerpt',
                'title' => 'Тип выполненных работ',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->excerpt ?? null
            ],
            [
                'name' => 'description',
                'title' => 'Описание',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $params->description ?? null
            ],
            [
                'name' => 'poster_id',
                'title' => 'Превью',
                'type' => FieldType::IMAGE,
                'required' => true,
                'value' => ($model->poster ?? null) ? fractal($model->poster, new AssetTransformer()) : null
            ],
        ];
        return ['data' => $fields];
    }


    public function store(array $data): ?JsonResponse {
        $page = Page::byUuid($data['attach']['page_id'])->first();
        $pub = [];
        $pub['page_id'] = $page->id;
        $pub['author_id'] = Auth::user()->id;
        $pub['type'] = PublicationType::PORTFOLIO;
        $pub['name'] = $data['name'];
        $pub['slug'] = Str::slug(Str::transliterate($data['name']));
        $pub['excerpt'] = $data['excerpt'];
        $pub['published_at'] = now();
        if (empty($data['poster_id'])) {
            $pub['poster_id'] = null;
        } else {
            $asset = Asset::query()->where(['uuid' => $data['poster_id']])->first();
            $pub['poster_id'] = $asset->id;
        }
        $params = [];
        if (!empty($data['description'])) {
            $params['description'] = $data['description'];
        }
        if (count($params) > 0) {
            $pub['params'] = json_encode($params);
        }
        $model = Publication::create($pub, true);
        return fractal($model, new PublicationTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Publication::byUuid($id)->firstOrFail();
        $pub = [];
        $pub['author_id'] = Auth::user()->id;
        $pub['slug'] = Str::slug(Str::transliterate($data['name']));
        $pub['excerpt'] = $data['excerpt'];
        if (!empty($data['name'])) {
            $pub['name'] = $data['name'];
        }
        if (empty($data['poster_id'])) {
            $pub['poster_id'] = null;
        } else {
            $asset = Asset::query()->where(['uuid' => $data['poster_id']])->first();
            $pub['poster_id'] = $asset->id;
        }
        $params = [];
        if (!empty($data['description'])) {
            $params['description'] = $data['description'];
        }
        if (count($params) > 0) {
            $pub['params'] = json_encode($params);
        }
        $model->update($pub);
        return fractal($model->fresh(), new PublicationTransformer())->respond();
    }
}
