<?php

class PolylangPolylangLanguageCreateProcessor extends modObjectCreateProcessor
{
    public $classKey = 'PolylangLanguage';
    public $languageTopics = array('polylang:default');
    public $beforeSaveEvent = 'OnBeforeSavePolylangLanguage';
    public $afterSaveEvent = 'OnSavePolylangLanguage';
    public $permission = 'polylang_language_save';
    /** @var Polylang $polylang */
    public $polylang;

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

    public function beforeSet()
    {
        $rank = $this->getProperty('rank', '');
        if (empty($rank)) {
            $rank = $this->modx->getCount($this->classKey) + 1;
            $this->setProperty('rank', $rank);
        }
        return true;
    }

    public function beforeSave()
    {
        $key = $this->getProperty('culture_key', '');
        $siteUrl = $this->getProperty('site_url', '');
        if ($this->modx->getCount($this->classKey, array('culture_key' => $key, 'site_url' => $siteUrl))) {
            $this->addFieldError('culture_key', $this->modx->lexicon('polylang_err_culture_key_exists'));
        }
        return !$this->hasErrors();
    }

    function afterSave()
    {
        $saved = parent::afterSave();
        if ($saved) {
            $id = $this->object->get('id');
            $languageGroup = $this->getProperty('language_group');
            $this->polylang->getTools()->createLexiconFile($this->object->get('culture_key'));
            if ($languageGroup) {
                $this->polylang->getTools()->addLanguageInGroups($id, $languageGroup);
            }
        }
        return $saved;
    }
}

return 'PolylangPolylangLanguageCreateProcessor';