<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (27.03.19)
* *
*
*  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
*  CONTACT                        ->       contact@modulesgarden.com
*
*
* This software is furnished under a license and may be used and copied
* only  in  accordance  with  the  terms  of such  license and with the
* inclusion of the above copyright notice.  This software  or any other
* copies thereof may not be provided or otherwise made available to any
* other person.  No title to and  ownership of the  software is  hereby
* transferred.
*
*
* ******************************************************************** */

namespace ModulesGarden\ProxmoxAddon\App\Services\Cloud;

use MGProvision\Proxmox\v2 as proxmox;
use ModulesGarden\ProxmoxAddon\App\Models\User;
use ModulesGarden\ProxmoxAddon\App\Repositories\Cloud\ProductConfigurationRepository;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\ProxmoxAddon\Core\Traits\Smarty;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

/**
 * Trait UserService
 * @method ProductConfigurationRepository configuration()
 */
trait UserService
{
    use Smarty;

    /**
     * @return User
     */
    protected function getUser()
    {
        $userId    = $this->getWhmcsParamByKey('userid');
        $serviceId = $this->getWhmcsParamByKey('serviceid');
        return User::ofUserId($userId)->ofHostingId($serviceId)->orderBy("id", "desc")->firstOrFail();
    }

    protected function isUser()
    {
        $userId    = $this->getWhmcsParamByKey('userid');
        $serviceId = $this->getWhmcsParamByKey('serviceid');
        return  User::ofUserId($userId)->ofHostingId($serviceId)->count()== 1;
    }

    /**
     * @return User
     * @throws proxmox\v2\ProxmoxApiException
     */
    public function userCreate(User $user = null)
    {
        if (is_null($user))
        {
            $user          = new User();
            $user->user_id = $this->getWhmcsParamByKey('userid');
        }
        $userPrefix = $this->configuration()->getUserPrefix();
        if ($userPrefix)
        {
            $userPrefix = $this->getSmarty()->fetchString($userPrefix, [
                "serviceid"  => $this->getWhmcsParamByKey('serviceid'),
                "service_id" => $this->getWhmcsParamByKey('serviceid')
            ]);
        }
        $user->hosting_id = $this->getWhmcsParamByKey('serviceid');
        $username =  $this->getWhmcsParamByKey('username');
        $user->username = $userPrefix .  $username;
        $password = $this->getWhmcsParamByKey('password', Utility::generatePassword(12));
        $user->setPassword($password);
        $user->realm = $this->configuration()->getRealm();
        $userService = new proxmox\models\User();
        $userService->setApi($this->api());
        $data = [
            "userid"    => "{$user->username}@{$user->realm}",
            "comment"   => $this->configuration()->getUserComment(),
            "email"     => $this->getWhmcsParamByKey('clientsdetails')['email'],
            "enable"    => 1,
            "firstname" => $this->getWhmcsParamByKey('clientsdetails')['firstname'],
            "lastname"  => $this->getWhmcsParamByKey('clientsdetails')['lastname'],
            "password" => $user->getPassword()
        ];
        $userService->create($data);
        $userService->changePassword($user->getPassword());
        $user->save();
        return $user;
    }

    protected function userUpdate()
    {
        $user        = $this->getUser();
        $userService = new proxmox\models\User("{$user->username}@{$user->realm}");
        $userService->setApi($this->api());
        try
        {
            $userService->changePassword($user->getPassword());
        }
        catch (\Exception $ex)
        {
            if (!preg_match('/No such user/', $ex->getMessage()))
            {
                throw $ex;
            }
            $this->userCreate($user);
        }

        if(!sl('Vm')->hasVm()){
            return ;
        }

        $vmid = sl('Vm')->getVm()->getVmid();
        $this->userUpdatePermission([$vmid]);
        return $this;
    }

    public function userUpdatePermission($vmIds){
        $user        = $this->getUser();
        $userService = new proxmox\models\User("{$user->username}@{$user->realm}");
        $userService->setApi($this->api());
        $permissions = $userService->permissions();
        foreach ($vmIds as $vmid){
            foreach ($permissions as $p)
            {
                if ($p['path'] == "/vms/" . $vmid && $p['ugid'] == $userService->getUserid())
                {
                    $userService->updatePermission($vmid, $p['roleid'], 1);
                }
            }
            $role = $this->configuration()->getUserRole();
            $userService->updatePermission($vmid, $role);
        }

        return $this;
    }

    protected function deleteUser()
    {
        $user        = $this->getUser();
        $userService = new proxmox\models\User("{$user->username}@{$user->realm}");
        $userService->setApi($this->api());
        $userService->delete();
        $user->delete();
        return $this;
    }


}