<?php
namespace Cockpit\Controller;

class RestApi extends \LimeExtra\Controller {

    protected function before() {
        $this->app->response->mime = 'json';
    }

    public function authUser() {

        $data = [ 'user' => $this->param('user'), 'password' => $this->param('password') ];

        if (!$data['user'] || !$data['password']) {
            return $this->stop(['error' => 'Missing user or password'], 412);
        }

        $user = $this->module('cockpit')->authenticate($data);

        if (!$user) {
            return $this->stop(['error' => 'Authentication failed'], 401);
        }

        return $user;
    }

    public function saveUser() {

        $data = $this->param('user', false);
        $user = $this->module('cockpit')->getUser();

        if (!$data) {
            return false;
        }

        if ($user) {

            $hasAccess = $this->module('cockpit')->hasaccess('cockpit', 'accounts');

            if (!isset($data['_id']) && !$hasAccess) {
                return $this->stop(401);
            }

            if (!$hasAccess && $data['_id'] != $user['_id'] ) {
                return $this->stop(401);
            }

            if (isset($data['_id'], $data['group']) && !$hasAccess) {
                unset($data['group']);
            }
        }

        $data['_modified'] = time();

        // new user needs a password
        if (!isset($data['_id'])) {

            // new user needs a password
            if (!isset($data['password'])) {
                return $this->stop(['error' => 'User password required'], 412);
            }

            // new user needs a username
            if (!isset($data['user']) || !trim($data['user'])) {
                return $this->stop(['error' => 'Username required'], 412);
            }

            $data = array_merge($account = [
                'user'   => 'admin',
                'name'   => '',
                'email'  => '',
                'active' => true,
                'group'  => 'user',
                'i18n'   => 'en'
            ], $data);

            if (isset($data['api_key'])) {
                $data['api_key'] = uniqid('account-').uniqid();
            }

            $data['_created'] = $data['_modified'];
        }

        if (isset($data['password'])) {

            if (strlen($data['password'])){
                $data['password'] = $this->app->hash($data['password']);
            } else {
                unset($data['password']);
            }
        }

        if (isset($data['email']) && !$this->app->helper('utils')->isEmail($data['email'])) {
            return $this->stop(['error' => 'Valid email required'], 412);
        }

        if (isset($data['user']) && !trim($data['user'])) {
            return $this->stop(['error' => 'Username cannot be empty!'], 412);
        }

        foreach (['name', 'user', 'email'] as $key) {
            if (isset($data[$key])) $data[$key] = strip_tags(trim($data[$key]));
        }

        // unique check
        // --
        $exists = $this->app->storage->find('cockpit/accounts', [
            'filter' => [
                '$or' => [
                    ['user'  => $data['user']],
                    ['email' => $data['email']],
                ]
            ],
            'limit' => 2
        ]);

        foreach ($exists as $e) {

            if (!isset($data['_id']) || $data['_id'] != $e['_id']) {
                $field = $e['user'] == $data['user'] ? 'Username' : 'Email';
                $this->app->stop(['error' =>  "{$field} is already used!"], 412);
            }
        }
        // --

        $this->app->trigger('cockpit.accounts.save', [&$data, isset($data['_id'])]);
        $this->app->storage->save('cockpit/accounts', $data);

        if (isset($data['password'])) {
            unset($data['password']);
        }

        return json_encode($data);
    }

    public function listUsers() {

        $user    = $this->module('cockpit')->getUser();
        $isAdmin = false;

        if ($user) {
            $isAdmin = $this->module('cockpit')->isSuperAdmin($user['group']);
        }

        $options = ['sort' => ['user' => 1]];

        if ($filter = $this->param('filter')) {

            $options['filter'] = $filter;

            if (is_string($filter)) {

                $options['filter'] = [
                    '$or' => [
                        ['name'  => ['$regex' => $filter]],
                        ['user'  => ['$regex' => $filter]],
                        ['email' => ['$regex' => $filter]],
                    ]
                ];
            }
        }

        $accounts = $this->app->storage->find('cockpit/accounts', $options)->toArray();

        foreach ($accounts as &$account) {

            if (isset($account['password']))     unset($account['password']);
            if (isset($account['api_key']))      unset($account['api_key']);
            if (isset($account['_reset_token'])) unset($account['_reset_token']);
        }

        return $accounts;
    }

    public function image() {

        $options = [
            'src'     => $this->param('src', false),
            'mode'    => $this->param('m', 'thumbnail'),
            'fp'      => $this->param('fp', null),
            'filters' => (array) $this->param('f', []),
            'width'   => intval($this->param('w', null)),
            'height'  => intval($this->param('h', null)),
            'quality' => intval($this->param('q', 100)),
            'rebuild' => intval($this->param('r', false)),
            'base64'  => intval($this->param('b64', false)),
            'output'  => intval($this->param('o', false))
        ];

        // Set single filter when available
        foreach ([
            'blur', 'brighten',
            'colorize', 'contrast',
            'darken', 'desaturate',
            'edge detect', 'emboss',
            'flip', 'invert', 'opacity', 'pixelate', 'sepia', 'sharpen', 'sketch'
        ] as $f) {
            if ($this->param($f)) $options[$f] = $this->param($f);
        }

        return $this->module('cockpit')->thumbnail($options);
    }

    public function assets() {

        $options = [
            'sort' => ['created' => -1]
        ];

        if ($filter = $this->param('filter', null)) $options['filter'] = $filter;
        if ($fields = $this->param('fields', null)) $options['fields'] = $fields;
        if ($limit  = $this->param('limit', null))  $options['limit'] = $limit;
        if ($sort   = $this->param('sort', null))   $options['sort'] = $sort;
        if ($skip   = $this->param('skip', null))   $options['skip'] = $skip;

        return $this->module('cockpit')->listAssets($options);
    }

    public function addAssets() {

        return $this->module('cockpit')->uploadAssets('files');
    }

    public function updateAssets() {

        if ($asset = $this->param('asset', false)) {
            return $this->module('cockpit')->updateAssets($asset);
        }

        return false;
    }

    public function removeAssets() {

        if ($assets = $this->param('assets', false)) {
            return $this->module('cockpit')->removeAssets($assets);
        }

        return false;
    }
}
