<?php

namespace Mnv\Models\Users;

use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\Exceptions\EmptyUserIdException;
use Mnv\Models\Users\Exceptions\NotUserApproveException;
use Mnv\Models\Users\Exceptions\UserNotDeletedException;

class SiteUser extends AbstractUser
{

    /**
     * Редактирование пользователя
     *
     * @throws NoUserException
     */
    public function edit(?string $userType)
    {
        if (!empty($this->userId)) {
            $this->get($userType);
            if (!empty($this->user)) {
                $this->getFiles();
            } else {
                throw new NoUserException();
            }
        }
    }


    public function prepare(array $data, int $managerId): bool
    {
        $data['modifiedBy']   = $managerId;
        $data['modifiedOn']   = gmdate('Y-m-d H:i:s');
        $data['userType']     = UserTypes::CUSTOMER;
        $data['accessLevel'] = 128;

        if (empty($this->userId)) {
            $data['password'] = \password_hash($data['password'], \PASSWORD_DEFAULT);
            $data['addedBy'] = $managerId;
            $data['addedOn'] = gmdate('Y-m-d H:i:s');
            $data['registered'] = strtotime(adjustTime(gmdate('Y-m-d H:i:s'), false));
            if ($this->insert($data)) {
                return true;
            }
        }
        else {
            if (!empty($data['password'])) {
                $data['password'] = \password_hash($data['password'], \PASSWORD_DEFAULT);
            } else {
                unset($data['password']);
            }
            if ($this->update($data)) {
                return true;
            }
        }

        return false;
    }


    /**
     * Удаление пользователя
     *
     *
     * @throws NoUserException
     * @throws EmptyUserIdException
     * @throws UserNotDeletedException
     */
    public function remove(?string $userType)
    {
        if (!empty($this->userId)) {
            $this->get($userType);
            if (!empty($this->user)) {
                if ( !$this->removeUser() ) {
                    throw new UserNotDeletedException();
                }
            } else {
                throw new NoUserException();
            }
        } else {
            throw new EmptyUserIdException();
        }

    }

    /**
     * Обновление статуса
     *
     * @throws NoUserException
     * @throws EmptyUserIdException
     * @throws NotUserApproveException
     */
    public function approve()
    {
        if (!empty($this->userId)) {
            $this->get();
            if (!empty($this->user)) {
                if (!$this->approveUser()) {
                    throw new NotUserApproveException();
                }
            }else {
                throw new NoUserException();
            }
        } else {
            throw new EmptyUserIdException();
        }

    }

}