<?php

namespace Concrete\Controller\SinglePage\Dashboard\System\Permissions;

use Concrete\Core\Antispam\Library as SystemAntispamLibrary;
use Concrete\Core\Page\Controller\DashboardPageController;
use Config;
use GroupList;
use Loader;

class Antispam extends DashboardPageController
{
    public function view()
    {
        $list = SystemAntispamLibrary::getList();
        $libraries = ['' => t('** None Activated')];
        foreach ($list as $sc) {
            $libraries[$sc->getSystemAntispamLibraryHandle()] = $sc->getSystemAntispamLibraryName();
        }
        $scl = SystemAntispamLibrary::getActive();
        $this->set('activeLibrary', $scl);
        $this->set('libraries', $libraries);

        $db = Loader::db();
        $groups = ['-1' => t('** None Selected')];
        $gl = new GroupList();
        $gl->sortBy('gID', 'asc');
        $gl->includeAllGroups();
        $res = $gl->getResults();
        foreach ($res as $g) {
            $groups[$g->getGroupID()] = $g->getGroupDisplayName(false);
        }
        $this->groups = $groups;
        $this->set('groups', $groups);
        $this->set('allowlistGroup', Config::get('concrete.spam.allowlist_group', Config::get('concrete.spam.whitelist_group')));
    }

    public function saved()
    {
        $this->set('message', t('Anti-spam settings saved.'));
        $this->view();
    }

    public function update_library()
    {
        $this->view();
        if (!isset($this->groups[$_POST['group_id']])) {
            $this->error->add('Invalid Group');
        }
        if (!$this->token->validate('update_library')) {
            $this->error->add($this->token->getErrorMessage());
        }
        if ($this->post('activeLibrary')) {
            $scl = SystemAntispamLibrary::getByHandle((string)$this->post('activeLibrary'));
            if (!$scl) {
                $this->error->add(t('Invalid anti-spam library'));
            }
        }

        if (!$this->error->has()) {
            Config::save('concrete.spam.allowlist_group', $_POST['group_id']);
            if ($this->post('activeLibrary')) {
                $scl = SystemAntispamLibrary::getByHandle($this->post('activeLibrary'));
                if ($scl instanceof SystemAntispamLibrary) {
                    $scl->activate();
                    Config::save('concrete.spam.notify_email', $this->post('ANTISPAM_NOTIFY_EMAIL'));
                    Config::save('concrete.log.spam', $this->post('ANTISPAM_LOG_SPAM'));
                    if ($scl->hasOptionsForm() && $this->post('ccm-submit-submit')) {
                        $controller = $scl->getController();
                        $controller->saveOptions($this->post());
                    }
                    $this->redirect('/dashboard/system/permissions/antispam', 'saved');
                }
            } else {
                SystemAntispamLibrary::deactivateAll();
            }
        }
    }
}
