<?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 PublicationSmiForms
    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' => 'published_at',
                'title' => 'Дата публикации',
                'type' => FieldType::DATE,
                'value' => $model->published_at ?? null,
                'required' => true,
            ],
            [
                'name' => 'name',
                'title' => 'Название',
                'type' => FieldType::STRING,
                'required' => true,
                'max_length' => 127,
                'value' => $model->name ?? null
            ],
            [
                'name' => 'excerpt',
                'title' => 'Краткое описание',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->excerpt ?? null
            ],
            [
                'name' => 'poster_id',
                'title' => 'Превью',
                'type' => FieldType::IMAGE,
                'required' => true,
                'value' => ($model->poster ?? null) ? fractal($model->poster, new AssetTransformer()) : null
            ],
            [
                'name' => 'url',
                'title' => 'Ссылка на сторонний ресурс',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $params->url ?? null
            ],
            [
                'name' => 'source',
                'title' => 'Название источника',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $params->source ?? 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::SMI;
        $pub['name'] = $data['name'];
        $pub['excerpt'] = $data['excerpt'];
        $pub['published_at'] = $data['published_at'];
        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['url'])) {
            $params['url'] = $data['url'];
        }
        if (!empty($data['source'])) {
            $params['source'] = $data['source'];
        }
        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;
        if (!empty($data['name'])) {
            $pub['name'] = $data['name'];
        }
        if (!empty($data['name'])) {
            $pub['name'] = $data['name'];
        }
        if (!empty($data['excerpt'])) {
            $pub['excerpt'] = $data['excerpt'];
        }
        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['url'])) {
            $params['url'] = $data['url'];
        }
        if (!empty($data['source'])) {
            $params['source'] = $data['source'];
        }
        if (count($params) > 0) {
            $pub['params'] = json_encode($params);
        }
        $pub['published_at'] = $data['published_at'];
        $model->update($pub);
        return fractal($model->fresh(), new PublicationTransformer())->respond();
    }
}
