<?php

class PolylangPolylangSeoPatternCloneProcessor extends modProcessor
{
    public $classKey = 'PolylangSeoPattern';
    public $permission = 'polylang_polylangseopattern_clone';
    /** @var Polylang $polylang */
    public $polylang;
    /** @var PolylangSeoPattern $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_polylangseopattern_err_nf', 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();
        $languages = $this->getProperty('languages');
        $data['template'] = $this->polylang->getTools()->getSeoTemplateIds($data['id']);
        foreach ($languages as $id => $val) {
            if (!$val) continue;
            $data['language_id'] = $id;
            /** @var modProcessorResponse $response */
            $response = $this->polylang->runProcessor('mgr/polylangseopattern/create', $data);
            if ($response->isError()) {
                return $this->failure($response->getMessage());
            }
        }

        return $this->success();
    }
}

return 'PolylangPolylangSeoPatternCloneProcessor';