<?php
/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Gebtu\Administrators;


class AdminController extends \Demotic\Controller
{

    public function index()
    {

        $administrators = Model::getAll();


        ipAddJs('Demotic/Gebtu/Core/assets/js/angular.js');
        ipAddJs('Demotic/Gebtu/Administrators/assets/administratorsController.js');

        foreach ($administrators as &$administrator) {
            unset($administrator['hash']);
            unset($administrator['resetSecret']);
            unset($administrator['resetTime']);
            $administrator['permissions'] = \Demotic\Gebtu\AdminPermissionsModel::getUserPermissions(
                $administrator['id']
            );
        }

        ipAddJsVariable('ipAdministrators', $administrators);
        ipAddJsVariable('ipAdministratorsAdminId', (int)ipAdminId());
        ipaddJsVariable('ipAvailablePermissions', \Demotic\Gebtu\AdminPermissionsModel::availablePermissions());
        ipaddJsVariable('ipAdministratorId', ipAdminId());
        ipaddJsVariable(
            'ipAdministratorsSuperAdminWarning',
            __('You will not be able to set other permissions for yourself!', 'Demotic-admin', false)
        );

        $data = array(
            'createForm' => Helper::createForm(),
            'updateForm' => Helper::updateForm()
        );
        return ipView('view/layout.php', $data)->render();

    }

    public function add()
    {
        ipRequest()->mustBePost();
        $post = ipRequest()->getPost();

        $form = Helper::createForm();
        $form->removeSpamCheck();

        $errors = $form->validate($post);

        if (!empty($errors)) {
            $data = array(
                'status' => 'error',
                'errors' => $errors
            );
            return new \Demotic\Response\Json($data);
        }


        $data = $form->filterValues($post);

        $username = $data['username'];
        $email = $data['email'];
        $password = $data['password'];

        $administratorId = Service::add($username, $email, $password);

        //set the same permissions as current administrator
        $curUserPermissions = \Demotic\Gebtu\AdminPermissionsModel::getUserPermissions(ipAdminId());
        foreach ($curUserPermissions as $permission) {
            \Demotic\Gebtu\AdminPermissionsModel::addPermission($permission, $administratorId);
        }


        $data = array(
            'status' => 'ok',
            'id' => $administratorId,
            'permissions' => \Demotic\Gebtu\AdminPermissionsModel::getUserPermissions($administratorId)
        );
        return new \Demotic\Response\Json($data);
    }

    public function delete()
    {
        ipRequest()->mustBePost();

        $userId = ipRequest()->getPost('id');

        if (!$userId) {
            throw new \Demotic\Exception('Missing required parameters');
        }

        if ($userId == ipAdminId()) {
            throw new \Demotic\Exception("Can't delete yourself");
        }

        Service::delete($userId);

        $data = array(
            'status' => 'ok'
        );
        return new \Demotic\Response\Json($data);
    }

    public function update()
    {
        ipRequest()->mustBePost();
        $post = ipRequest()->getPost();

        if (!isset($post['id']) || !isset($post['username']) || !isset($post['email'])) {
            throw new \Demotic\Exception('Missing required parameters');
        }


        $form = Helper::updateForm();
        $form->removeSpamCheck();
        $errors = $form->validate($post);

        $userId = $post['id'];
        $username = $post['username'];
        $email = $post['email'];
        if (isset($post['password'])) {
            $password = $post['password'];
        } else {
            $password = null;
        }


        $existingUser = Service::getByUsername($username);
        if ($existingUser && $existingUser['id'] != $userId) {
            $errors['username'] = __('Already taken', 'Demotic-admin', false);
        }

        if ($errors) {
            $data = array(
                'status' => 'error',
                'errors' => $errors
            );
            return new \Demotic\Response\Json($data);
        }

        Service::update($userId, $username, $email, $password);

        $data = array(
            'status' => 'ok'
        );
        return new \Demotic\Response\Json($data);
    }

    public function setAdminPermission()
    {
        ipRequest()->mustBePost();
        $post = ipRequest()->getPost();

        if (!isset($post['permission']) || !isset($post['value']) || !isset($post['adminId'])) {
            throw new \Demotic\Exception('Missing required parameters');
        }

        $permission = $post['permission'];
        $value = $post['value'];
        $adminId = $post['adminId'];

        if ($value) {
            \Demotic\Gebtu\AdminPermissionsModel::addPermission($permission, $adminId);
        } else {
            \Demotic\Gebtu\AdminPermissionsModel::removePermission($permission, $adminId);
        }

        $data = array(
            'status' => 'ok'
        );
        return new \Demotic\Response\Json($data);

    }
}
