<?php

namespace Pages\Controller;

use App\Controller\App;
use ArrayObject;

class Utils extends App {

    public function find() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $options = \array_merge([
            'limit' => 20
        ], $this->param('options', []));

        if (isset($options['filter']) && \is_string($options['filter']) && $options['filter']) {

            $filter = null;

            if (\preg_match('/^\{(.*)\}$/', $options['filter'])) {

                try {
                    $filter = json5_decode($options['filter'], true);
                } catch (\Exception $e) {}
            }

            if (!$filter) {

                $terms = \str_getcsv(\trim($options['filter']), ' ', escape: '\\');

                $filter = ['$or' => []];

                foreach ($terms as $term) {
                    $filter['$or'][] = [
                        '$or' => [
                            ['title' => ['$regex' => $term, '$options' => 'i']],
                            ['slug' => ['$regex' => $term, '$options' => 'i']],
                            ['type' => $term],
                        ]
                    ];
                }
            }

            $options['filter'] = $filter;
        }

        if (isset($options['pageType']) && $options['pageType']) {
            $options['filter'] = !isset($options['filter']) || !$options['filter'] ? [] : $options['filter'];
            $options['filter']['type'] = $options['pageType'];
        }

        $items = $this->app->dataStorage->find('pages', $options)->toArray();
        $count = (!isset($options['skip']) && !isset($options['limit'])) ? \count($items) : $this->app->dataStorage->count('pages', isset($options['filter']) ? $options['filter'] : []);
        $pages = isset($options['limit']) ? \ceil($count / $options['limit']) : 1;
        $page  = 1;

        if ($pages > 1 && isset($options['skip'])) {
            $page = \ceil($options['skip'] / $options['limit']) + 1;
        }

        if (\count($items) && isset($options['locale']) && $options['locale']) {
            $items = $this->helper('locales')->applyLocales($items, $options['locale']);
        }

        return \compact('items', 'count', 'pages', 'page');
    }

    public function updateOrder() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $pages = $this->param('pages', null);

        if (!\is_array($pages)) {
            return false;
        }

        $updatePageRoute = null;

        foreach ($pages as $page) {

            if (!isset($page['_id'], $page['_o'])) continue;

            $item = [
                '_id' => $page['_id'],
                '_o' => $page['_o']
            ];

            if (\array_key_exists('_pid', $page)) {
                $item['_pid'] = $page['_pid'];
                $updatePageRoute = $item['_id'];
            }

            $this->app->dataStorage->save('pages', $item);
        }

        if ($updatePageRoute) {
            $this->helper('pages')->updateRoutes($updatePageRoute);
        }

        return ['success' => true];
    }

    public function pageTypes() {
        return $this->module('pages')->pageTypes();
    }
}
