<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Entities\Registracia\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;
use Seka\Portal\Modul\Terminy\Entities\Registracia\ValueObjects\ZoznamZvolenychMoznostiUdalostiValueObject;

/**
 * Class ZvoleneMoznostiUdalostiCast
 *
 * @package Seka\Portal\Modul\Terminy\Entities\Registracia\Casts
 */
final class ZvoleneMoznostiUdalostiCast implements CastsAttributes
{
    /**
     * @param        $model
     * @param string $key
     * @param        $value
     * @param array  $attributes
     *
     * @return \Illuminate\Support\Collection
     */
    public function get($model, string $key, $value, array $attributes): Collection
    {
        $coll = collect([]);
        $val = json_decode($value ?? '');

        if (!is_array($val)) return $coll;

        foreach ($val as $zoznamMoznostiUdalosti) {
            $coll->add(
                ZoznamZvolenychMoznostiUdalostiValueObject::fromJSON(
                    $zoznamMoznostiUdalosti->nazov,
                    $zoznamMoznostiUdalosti->kod,
                    $zoznamMoznostiUdalosti->moznosti,
                )
            );
        }

        return $coll;
    }

    /**
     * @param        $model
     * @param string $key
     * @param        $value
     * @param array  $attributes
     *
     * @return false|string
     */
    public function set($model, string $key, $value, array $attributes): bool|string
    {
        $out = collect([]);

        if ($value instanceof Collection) {
            $out = $value->map(function (ZoznamZvolenychMoznostiUdalostiValueObject $moznost) {
                return [
                    'nazov' => $moznost->getNazov(),
                    'kod' => $moznost->getKod(),
                    'moznosti' => $moznost->getMoznosti(),
                ];
            });
        }

        return json_encode($out->toArray());
    }
}
