<?php
namespace MotoPlugin\MotoTeam\AdvancedContactForm;

use Moto;

class Widget extends Moto\System\Widgets\AbstractFormWidget
{
    protected $_name = 'moto_team@advanced_contact_form';
    protected static $_defaultProperties = array(
        '_form_fields_' => array(),
        'preset' => 'default',
        'customDesign' => array(
            'enabled' => false,
        ),
        'settings' => array(
            'recipient' => '',
        ),
        'visible_on' => 'mobile-v',
        'spacing' => array(
            'top' => 'auto',
            'right' => 'auto',
            'bottom' => 'auto',
            'left' => 'auto',
        ),
        'postAction' => array(
            'action' => 'none',
            'properties' => array(
                'id' => '',
                'target' => '_self',
            ),
        ),
        'resetAfterSubmission' => false
    );
    protected $_templateType = 'templates';

    protected $_widgetId = true;

    public function getTemplatePath($preset = null)
    {
        return '@plugins/moto_team/advanced_contact_form/templates/default.twig.html';
    }
    public function preRender()
    {
        parent::preRender();
        $this->saveStorageFile();
    }
    public function getContactFormAccessToken()
    {
        $data = array(
            'id' => $this->getWidgetId(),
            'name' => $this->getName(),
            'hash' => $this->_getSensitiveSettingsHash(),
        );

        return Moto\System::encrypt($data);
    }

    protected function _getSensitiveSettingsHash()
    {
        return sha1(json_encode($this->properties['_form_fields_']));
    }
    public function saveStorageFile($force = false)
    {
        if ($force) {
            $isNeedSave = true;
        } else {
            $isNeedSave = Moto\System\Widgets\Storage::getById($this->getWidgetId(), 'hash') !== $this->_getSensitiveSettingsHash();
        }

        if ($isNeedSave) {
            return Moto\System\Widgets\Storage::saveByWidget($this, array(
                'hash' => $this->_getSensitiveSettingsHash(),
                'properties' => $this->properties,
            ));
        }

        return true;
    }

    public function getActionAfterSubmission()
    {
        $clickAction = Moto\ClickAction\Factory::create($this->properties['postAction']);
        $data = $clickAction->toArray(['url', 'target']);
        $data['id'] = Moto\Util::getValue($data, 'properties.id');

        return Moto\Util::arrayOnly($data, ['action', 'url', 'target', 'id']);
    }
    public function exportSettings()
    {
        $settings = array(
            'validationMessages' => $this->getPropertyValue('settings.validationMessages'),
            'events' => $this->getPropertyValue('settings.events'),
            'actionAfterSubmission' => $this->getActionAfterSubmission(),
            'resetAfterSubmission' => $this->properties['resetAfterSubmission']
        );

        return $settings;
    }
}
