<?php

namespace App\Services\Forms\Applications;

use App\Models\Applications\Application;
use App\Models\Applications\ApplicationStatus;
use App\Models\Companies\CompanyMember;
use App\Models\Objects\Field;
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 App\Transformers\Companies\CompanyMemberTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Spatie\Fractal\Fractal;

class ExpertForms 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)]
            ]
        ];
    }

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

    public function commonGroupFields(?Application $model): array {
        $fields = [
            [
                'name' => 'expert',
                'title' => 'Эксперт',
                'type' => FieldType::RELATION,
                'required' => true,
                'options' => $this->getExperts(),
                'value' => ($v = $model->expert ?? null) ? fractal($v, new CompanyMemberTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }


    public function getExperts(): Fractal {
        return fractal(CompanyMember::query()->mainCompany()->whereHas('objects', function($query) {
            Field::applyFilters($query, collect(['types' => 'company-member-properties', 'moderate-permissions' => 'applications']));
        })->get(), new CompanyMemberTransformer());
    }


    public function store(array $data) {
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Application::byUuid($id)->firstOrFail();
        if ($expert = CompanyMember::byUuid($data['expert'] ?? null)->first()) $model->setExpert($expert);
        return fractal($model, new ApplicationTransformer())->respond();
    }
}
