<?php

class PolylangPolylangContentLanguagesProcessor extends modProcessor
{
    public $languageTopics = array('polylang:default');
    /** @var Polylang $polylang */
    public $polylang;
    /** @var PolylangTools $tools */
    public $tools = null;

    public function initialize()
    {
        $initialized = parent::initialize();
        $this->polylang = $this->modx->getService('polylang', 'Polylang');
        $this->tools = $this->polylang->getTools();
        $this->setDefaultProperties(array(
            'sort' => 'Language.rank',
            'dir' => 'ASC',
        ));
        return $initialized;
    }

    public function process()
    {
        $rid = $this->getProperty('rid', 0);
        $mode = $this->getProperty('mode');
        $exclude = $this->getProperty('exclude', '');
        $exclude = $this->tools->explodeAndClean($exclude);
        $allLanguages = $this->tools->getLanguages(false, array(
            'sort' => 'rank'
        ));
        $contentLanguages = $this->getContentLanguages($rid, $exclude);
        $contentLanguages = array_flip($contentLanguages);

        switch ($mode) {
            case 'lacking':
                $languages = array_diff_key($allLanguages, $contentLanguages);
                break;
            case 'exist':
                $languages = array_intersect_key($allLanguages, $contentLanguages);
                break;
            default:
                $languages = array_diff_key($allLanguages, array_flip($exclude));

        }
        return $this->success('', array('rid' => $rid, 'languages' => $languages));
    }

    /**
     * @param int $rid
     * @param array $exclude
     *
     * @return array
     */
    public function getContentLanguages($rid, array $exclude = array())
    {
        $result = array();
        $classKey = 'PolylangContent';
        $sort = $this->getProperty('sort');
        $dir = $this->getProperty('dir');
        $q = $this->modx->newQuery($classKey);
        $q->leftJoin('PolylangLanguage', 'Language', '`Language`.`culture_key` = `PolylangContent`.`culture_key`');
        $q->select($this->modx->getSelectColumns($classKey, $classKey, '', array('culture_key')));
        $q->where(array(
            '`content_id`' => $rid
        ));
        if ($exclude) {
            $q->where(array(
                '`culture_key`:NOT IN' => $exclude
            ));
        }
        $q->sortby($sort, $dir);
        if ($q->prepare() && $q->stmt->execute()) {
            $result = $q->stmt->fetchAll(PDO::FETCH_COLUMN);
        }
        return $result;
    }
}

return 'PolylangPolylangContentLanguagesProcessor';