<?php

class PolylangPolylangLanguageRemoveProcessor extends modObjectRemoveProcessor
{
    public $classKey = 'PolylangLanguage';
    public $languageTopics = array('polylang:default');
    public $beforeRemoveEvent = 'OnBeforeRemovePolylangLanguage';
    public $afterRemoveEvent = 'OnRemovePolylangLanguage';
    public $permission = 'polylang_language_remove';
    /** @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 afterRemove()
    {
        $removed = parent::afterRemove();
        if ($removed) {
            $sql = "UPDATE {$this->modx->getTableName($this->classKey)} SET `rank`=`rank`-1 WHERE `rank`>{$this->object->get('rank')}";
            $this->modx->exec($sql);
            $cultureKey = $this->object->get('culture_key');
            if (!$this->languageExists()) {
                $classes = $this->polylang->getTools()->getContentClasses();
                $classes = array_values($classes);
                $classes = array_merge($classes, array(
                    'PolylangProductOption',
                    'PolylangTv',
                    'PolylangTvTmplvars',
                ));
                foreach ($classes as $classKey) {
                    $this->modx->removeCollection($classKey, array('culture_key' => $cultureKey));
                }
                $this->polylang->getTools()->removeLexiconFile($this->object->get('culture_key'));
            }
        }
        return $removed;
    }

    /**
     * @return bool
     */
    public function languageExists()
    {
        return (bool)$this->modx->getCount($this->classKey, array(
            'culture_key' => $this->object->get('culture_key')
        ));
    }

}

return 'PolylangPolylangLanguageRemoveProcessor';