<?php

$this->on('pages.page.save', function($page, $isUpdate) {

    $indexes = $this->module('detektivo')->indexes();
    $toUpdate = array_filter($indexes, function($index) {
        return $index['type'] === 'pages';
    });

    if (!count($toUpdate)) return;

    $settings = $this->module('pages')->settings();
    $locales = array_keys($this->helper('locales')->locales(true));

    $documents = [];

    foreach ($locales as $locale) {

        $_page = $this->helper('pages')->processPage($page, ['locale' => $locale, 'limit' => 1000]);
        $_page['id'] = $_page['_id'].($locale == 'default' ? '' : "_{$locale}");
        $_page['locale'] = $locale;

        if ($locale !== 'default' && (
            (isset($settings['locales'][$locale]) && $settings['locales'][$locale] === false) || // is locale disabled globally?
            (isset($page['_locales'][$locale]) && $page['_locales'][$locale] === false) // is locale disabled for this page?
        )) {
            continue;
        }

        unset($_page['_id']);

        $documents[] = $_page;

        if (isset($_page['data']['items']) && is_array($_page['data']['items'])) {

            foreach ($_page['data']['items'] as $item) {

                if (isset($item['route'])) {
                    $p = $this->module('pages')->pageByRoute($item['route'], ['locale' => $locale]);

                    if ($p) {
                        $p['_r'] = $item['route'];
                        $p['id'] = $p['_id'].($locale == 'default' ? '' : $locale);
                        $p['locale'] = $locale;

                        unset($p['_id']);
                        $documents[] = $p;
                    }
                }
            }
        }
    }

    foreach ($toUpdate as $index) {

        $idx = $this->module('detektivo')->index($index['name']);

        foreach ($documents as $doc) {
            $idx->addDocument($doc['id'], $doc, $isUpdate);
        }
    }

});

$this->on('pages.remove', function(array $pageIds) {

    $indexes = $this->module('detektivo')->indexes();
    $toUpdate = array_filter($indexes, function($index) {
        return $index['type'] === 'pages';
    });

    if (!count($toUpdate)) return;

    $locales = [];

    foreach ($this->helper('locales')->locales() as $locale) {
        if ($locale['i18n'] == 'default') continue;
        $locales[] = $locale['i18n'];
    }

    $ids = [];

    foreach ($pageIds as $id) {

        $ids[] = $id;

        foreach ($locales as $locale) {
            $ids[] = "{$id}_{$locale}";
        }
    }

    foreach ($toUpdate as $index) {

        $idx = $this->module('detektivo')->index($index['name']);

        foreach ($ids as $id) {
            $idx->removeDocument($id);
        }
    }
});
