<?php

class PolylangLexiconEntriesUpdateProcessor extends modProcessor
{
    /** @var Polylang $polylang */
    public $polylang;
    public $permission = 'polylang_lexicon_save';

    public function initialize()
    {
        if (!$this->modx->hasPermission($this->permission)) {
            return $this->modx->lexicon('access_denied');
        }
        // $this->polylang = $this->modx->getService('polylang', 'Polylang');
        $this->setDefaultProperties(array(
            'namespace' => 'polylang',
            'topic' => 'site',
        ));
        return parent::initialize();
    }

    public function getLanguageTopics()
    {
        return array('polylang:default');
    }

    public function process()
    {
        $namespace = $this->getProperty('namespace');
        $language = $this->getProperty('language');
        $topic = $this->getProperty('topic');
        $name = $this->getProperty('name');
        $value = $this->getProperty('value');

        $entries = $this->modx->lexicon->getFileTopic($language, $namespace, $topic);

        /** @var modLexiconEntry $entry */
        $entry = $this->modx->getObject('modLexiconEntry', array(
            'name' => $name,
            'namespace' => $namespace,
            'language' => $language,
            'topic' => $topic,
        ));
        /* if entry is same as file, remove db custom */
        if (!empty($entries[$name]) && $entries[$name] == $value) {
            if ($entry) {
                $entry->remove();
                $entry->clearCache();
            }
        } else {
            if ($entry == null) {
                $entry = $this->modx->newObject('modLexiconEntry');
                $entry->set('name', $name);
                $entry->set('namespace', $namespace);
                $entry->set('language', $language);
                $entry->set('topic', $topic);
            }
            $entry->set('editedon', date('Y-m-d H:i:s'));
            $entry->set('value', $value);

            if (!$entry->save()) {
                return $this->failure($this->modx->lexicon('polylang_lexiconentries_err_save'));
            }

            /* clear cache */
            $entry->clearCache();
        }
        return $this->success('', $entry);
    }
}

return 'PolylangLexiconEntriesUpdateProcessor';