<?php

class PolylangPolylangSeoPatternUpdateProcessor extends modObjectUpdateProcessor
{
    public $classKey = 'PolylangSeoPattern';
    public $languageTopics = array('polylang:default');
    public $permission = 'polylang_polylangseopattern_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()
    {
        if ($this->exists()) {
            return $this->modx->lexicon('polylang_polylangseopattern_err_exists');
        }
        return true;
    }

    public function afterSave()
    {
        $templates = $this->getProperty('template', array());
        if ($templates) {
            $patternId = $this->object->get('id');
            $table = $this->modx->getTableName('PolylangSeoPatternTemplate');
            $this->modx->exec("DELETE FROM {$table} WHERE `pattern_id` = {$patternId};");
            
            foreach ($templates as $template) {
                $obj = $this->modx->newObject('PolylangSeoPatternTemplate');
                $obj->set('template_id', $template);
                $obj->set('pattern_id', $patternId);
                if (!$obj->save()) {
                    $this->modx->log(modX::LOG_LEVEL_ERROR, '[PolylangSeoPatternTemplate] Error save!');
                }
            }
        }
        return parent::afterSave();
    }

    /**
     * @return bool
     */
    public function exists()
    {
        $id = $this->object->get('id');
        $fieldId = $this->getProperty('field_id');
        $languageId = $this->getProperty('language_id');
        $templates = $this->getProperty('template', array());

        $classKey = 'PolylangSeoPattern';
        $q = $this->modx->newQuery($classKey);
        $q->leftJoin('PolylangSeoPatternTemplate', 'PatternTemplate', "`PatternTemplate`.`pattern_id` = `{$classKey}`.`id`");

        $q->select($this->modx->getSelectColumns($classKey, $classKey));

        $q->where(array(
            "`{$classKey}`.`id`:!=" => $id,
            "`{$classKey}`.`field_id`" => $fieldId,
            "`{$classKey}`.`language_id`" => $languageId,
            "`PatternTemplate`.`template_id`:IN" => $templates,
        ));

        return (bool)$this->modx->getCount($classKey, $q);
    }


}

return 'PolylangPolylangSeoPatternUpdateProcessor';