<?php

declare(strict_types=1);

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

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

/**
 * Class MoznostiUdalostiCast
 *
 * @package Seka\Portal\Modul\Terminy\Entities\Udalost\Casts
 */
final class MoznostiUdalostiCast implements CastsAttributes
{
    /**
     * @param        $model
     * @param string $key
     * @param        $value
     * @param array  $attributes
     *
     * @return \Seka\Portal\Modul\Terminy\Entities\Udalost\ValueObjects\ZoznamMoznostiUdalostiValueObject|null
     */
    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(
                ZoznamMoznostiUdalostiValueObject::make(
                    $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)
    {
        if (! $value instanceof Collection) return false;

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

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