<?php

namespace App\Services\Forms;

use App\Services\Forms\Advisories\AdvisoryFormsServices;
use App\Services\Forms\Companies\CompanyFormsServices;
use App\Services\Forms\Feedback\FeedbackFormsServices;
use App\Services\Forms\Pages\PageFormsServices;
use App\Services\Forms\Publications\PublicationFormsServices;
use App\Services\Forms\Registries\RegistryFormsServices;
use App\Services\Forms\Users\UserFormsServices;

class FormsService {
    public array $formTitles = ['create' => '', 'update' => ''];

    public static array $services = [
        PageFormsServices::class,
        PublicationFormsServices::class,
        RegistryFormsServices::class,
        UserFormsServices::class,
        FeedbackFormsServices::class,
        AdvisoryFormsServices::class,
        CompanyFormsServices::class
    ];

    public function __construct() {

    }

    public static function getService($type) {
        foreach (self::$services as $service) {
            $services = $service::$services;
            if (($class = $services[$type] ?? null) && class_exists($class)) return new $class();
        }
        return null;
    }


    public function formTitle($model = null): ?string {
        return $this->formTitles[$model ? 'update' : 'create'] ?? null;
    }


    public function form(?string $id = null, array $data = []): array {
        return [];
    }

    public function save(array $data, ?string $id = null) {
        return $id ? $this->update($id, $data) : $this->store($data);
    }

    public function store(array $data) {
        return null;
    }

    public function update(string $id, array $data) {
        return null;
    }


    protected function getRelationItems(array $items): array {
        return ['data' => collect($items)->map(function($title, $name) {
            return ['id' => $name, 'title' => $title];
        })->values()->all()];
    }

    protected function getRelationValue(array $items, ?string $id): array {
        return ['data' => collect($items)->filter(function($title, $name) use ($id) {
            return $name == $id;
        })->map(function($title, $name) {
            return ['id' => $name, 'title' => $title];
        })->values()->all()];
    }


}
