<?php

namespace Inbox\Controller;

class Submissions extends Controller {

    protected function before() {

        if (!$this->isAllowed('inbox/submissions')) {
            return $this->stop(401);
        }
    }

    public function form( $id = null) {

        if (!$id) {
            return false;
        }

        $form = $this->app->dataStorage->findOne('inbox/forms', ['_id' => $id]);

        if (!$form) {
            return false;
        }

        return $this->render('inbox:views/submissions/form.php', \compact('form'));

    }

    public function load($formId = null) {

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

        if (!$formId) {
            return false;
        }

        $form = $this->app->dataStorage->findOne('inbox/forms', ['_id' => $formId]);

        if (!$form) {
            return false;
        }

        $collection = "inbox/form_{$formId}";
        $options = $this->app->param('options', []);
        $fields = $form['security']['fields'] ?? [];

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

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

            $filter = null;

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

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

            if (!$filter && \count($fields)) {

                $filter = null;

                if (\count($fields)) {

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

                    foreach ($fields as $field) {

                        foreach ($terms as $term) {
                            $f = [];
                            $f['data.'.$field] = ['$regex' => $term, '$options' => 'i'];
                            $filter['$or'][] = $f;
                        }
                    }
                }
            }

            $options['filter'] = \array_merge($filter, $options['filter']);
        }

        //return $options;

        $items = $this->app->dataStorage->find($collection, $options)->toArray();
        $count = $this->app->dataStorage->count($collection, $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;
        }

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

    public function remove($formId = null) {

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

        $ids = $this->param('ids');

        if (!$form || !\is_array($ids)) {
            return false;
        }

        if (!$ids) {
            return $this->stop(['error' => 'Item ids to delete are missing'], 412);
        }

        $this->app->dataStorage->remove("inbox/form_{$formId}", ['_id' => ['$in' => $ids]]);

        return ['success' => true];
    }

}
