<?php

class PolylangPolylangLanguageCloneProcessor extends modProcessor
{
    public $classKey = 'PolylangLanguage';
    public $permission = 'polylang_language_clone';
    /** @var Polylang $polylang */
    public $polylang;
    /** @var PolylangLanguage $source */
    public $source;

    public function initialize()
    {
        if (!$this->modx->hasPermission($this->permission)) {
            return $this->modx->lexicon('access_denied');
        }
        $initialized = parent::initialize();
        if ($initialized) {
            $id = $this->getProperty('id');
            $this->source = $this->modx->getObject($this->classKey, $id);
            if (!$this->source) {
                $initialized = $this->modx->lexicon('polylang_err_nf_language', array('id' => $id));
            }
            $this->polylang = $this->modx->getService('polylang', 'Polylang');
        }
        return $initialized;
    }

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

    public function process()
    {
        $data = $this->source->toArray();
        $data = array_merge($data, array(
            'culture_key' => $this->getProperty('culture_key'),
            'site_url' => $this->getProperty('site_url'),
        ));
        $data['language_group'] = $this->polylang->getTools()->getLanguageGroupField($this->source->get('id'));
        /** @var modProcessorResponse $response */
        $response = $this->polylang->runProcessor('mgr/polylanglanguage/create', $data);
        if ($response->isError()) {
            return $this->failure($response->getMessage());
        }
        return $this->success();
    }
}

return 'PolylangPolylangLanguageCloneProcessor';