<?php

namespace Inbox\Controller;

class Forms extends Controller {

    protected function before() {

        if (!$this->isAllowed('inbox/manage')) {
            return $this->stop(401);
        }
    }

    public function form($id = null) {

        $form = [
            'token' => null,
            'name' => '',
            'group' => '',
            'color' => '',
            'info' => '',
            'notify' => [
                'emails' => [],
            ],
            'security' => [
                'domains' => [],
                'fields' => [],
                'honeypot' => null,
                'languages' => [],
            ],
            '_state' => 0
        ];

        if ($id) {

            $frm = $this->app->dataStorage->findOne('inbox/forms', ['_id' => $id]);

            if (!$frm) {
                return false;
            }

            $form = array_merge($form, $frm);
        }

        $groups = $this->getGroups();

        $_locales = include($this->path('system:data/locales.php'));

        $supported = [
            'am', 'ar', 'az',
            'be', 'bg', 'bn',
            'ca', 'cs',
            'da', 'de',
            'el', 'en', 'es', 'et', 'eu',
            'fa', 'fi', 'fr',
            'gu',
            'he', 'hi', 'hr', 'hu', 'hy',
            'is', 'it',
            'ja',
            'ka', 'kn', 'ko', 'ku',
            'lo', 'lt', 'lv',
            'ml', 'mr', 'ms',
            'nl', 'no',
            'or',
            'pa', 'pl', 'pt',
            'ro', 'ru',
            'sk', 'sl', 'sq', 'sr', 'sv',
            'ta', 'te', 'th', 'tl', 'tr',
            'uk', 'ur',
            'vi',
            'yo',
            'zh'
        ];

        $locales = [];

        foreach ($supported as $i18n) {

            if (!isset($_locales[$i18n])) continue;

            $loc = $_locales[$i18n];

            $locales[] = [
                'value' => $i18n,
                'label' => $loc['name'].' ('.$loc['native'].')'
            ];
        }

        return $this->render('inbox:views/forms/form.php', compact('form', 'groups', 'locales'));
    }

    public function save() {

        $this->hasValidCsrfToken(true);

        $form = $this->param('form');

        if (!$form) {
            return false;
        }

        $form['_modified'] = time();
        $form['_mby'] = $this->user['_id'];

        if (!isset($form['_id'])) {
            $form['token'] = bin2hex(random_bytes(20));
            $form['_created'] = $form['_modified'];
            $form['_cby'] = $this->user['_id'];
        }

        if (isset($form['notify']['emails']) && is_array($form['notify']['emails'])) {
            $form['notify']['emails'] = array_unique(array_filter($form['notify']['emails'], function($email) {
                return $email && filter_var($email, FILTER_VALIDATE_EMAIL);
            }));
        }

        if (isset($form['security']['domains']) && is_array($form['security']['domains'])) {

            $form['security']['domains'] = array_unique(array_filter($form['security']['domains'], function($domain) {
                return $domain && filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
            }));
        }

        if (isset($form['security']['fields']) && is_array($form['security']['fields'])) {

            $form['security']['fields'] = array_unique(array_filter($form['security']['fields'], function($field) {
                return $field && $field === preg_replace('/[^A-Za-z0-9_]/', '', $field);
            }));
        }

        if (isset($form['security']['languages']) && is_array($form['security']['languages'])) {

            $form['security']['languages'] = array_unique(array_filter($form['security']['languages'], function($lang) {
                return $lang && $lang === preg_replace('/[^A-Za-z0-9_]/', '', $lang);
            }));
        }

        $this->app->dataStorage->save('inbox/forms', $form);

        $this->helper('eventStream')->add('inbox.forms.updated', ['action' => 'save', 'name' => $form['name']]);

        return $form;
    }

    public function remove() {

        $this->hasValidCsrfToken(true);

        $form = $this->param('form');

        if (!$form || !isset($form['_id'], $form['name'])) {
            return $this->stop(['error' => 'form is missing'], 412);
        }

        $this->app->dataStorage->remove('inbox/forms', ['_id' => $form['_id']]);
        $this->app->dataStorage->dropCollection("inbox/form_{$form['_id']}");
        $this->helper('eventStream')->add('inbox.forms.updated', ['action' => 'remove', 'name' => $form['name']]);

        return ['success' => true];
    }

    protected function getGroups() {

        $groups = [];

        $forms = $this->app->dataStorage->find('inbox/forms', ['sort' => ['name' => 1]])->toArray();

        foreach ($forms as $form) {

            if (isset($form['group']) && $form['group'] && !\in_array($form['group'], $groups)) {
                $groups[] = $form['group'];
            }
        }

        sort($groups);

        return $groups;
    }
}
