<?php

namespace Solspace\Freeform\Bundles\Form\Security;

use Solspace\Freeform\Events\FormEventInterface;
use Solspace\Freeform\Form\Form;
use Solspace\Freeform\Library\Bundles\FeatureBundle;
use Solspace\Freeform\Library\Helpers\CryptoHelper;
use yii\base\Event;

class FormSecret extends FeatureBundle
{
    public const KEY = 'secret';

    public function __construct()
    {
        Event::on(Form::class, Form::EVENT_FORM_LOADED, [$this, 'addSecret']);
    }

    public static function get(Form $form)
    {
        return $form->getProperties()->get(self::KEY);
    }

    public function addSecret(FormEventInterface $event): void
    {
        $secret = CryptoHelper::getUniqueToken(20);
        $event->getForm()->getProperties()->set(self::KEY, $secret);
    }
}
