<?php  

namespace App\Business\UserProfile\Users;

use App\Business\UserProfile\UserPermissions\PermissionGetter;
use App\Business\UserProfile\UserPermissions\PermissionsService;
use App\Exceptions\BadPasswordException;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserService{
    
    public function makeLogin($request){
        $password = $request->password;
        $email = $request->email;
        
        $token = null;

        $user = UserGetter::getUserByEmail($email);

        if($user && $user->is_active){
            if (!$token = Auth::guard('web')->attempt(request(['email', 'password']))) {
                throw new BadPasswordException("Contraseña incorrecta", 401);
            }
        }else{
            throw new BadPasswordException("Contraseña incorrecta", 401);
        }

        $permissions = PermissionGetter::getPermmisionByUser($user->id);
        $permissionsModel = [];
        foreach ($permissions as $p) {
            $permissionsModel[] = $p->id;
        }

        return $this->respondWithToken($token, $permissionsModel);
        return $token;
    }

    protected function respondWithToken($token, $actions)
    {
        return [
            'token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('web')->factory()->getTTL() * 60,
            'actions' => $actions
        ];
    }

    public static function listUserByAccount(){
       try {
            $user = Auth::user();
            $users = null;
            if ($user->user_type == 1) {
                $users = UserGetter::getAllUsersByAccount($user->account_id);
            } else {
                $users = UserGetter::getUserById($user->id);
            }

            return $users;
       } catch (\Throwable $th) {
            throw new Exception("Error Processing Request", 1);            
       }
    }

    public static function createUser($user, $password, $name, $email, $phone, $manager, $admin, $web, $movil){
        try {
            $existed = UserGetter::getUserByEmail($email);
            if($existed != null) throw new Exception("El usuario con correo {$email} ya existe en sistema", 1);
            
            $userModel = null;
            $userOrignModel = null;
            $userData = Auth::user();
            $permissions = [];
            if ($admin) $permissions[] = 1;
            if ($web) $permissions[] = 2;
            if ($movil) $permissions[] = 3;
            DB::transaction(function () use (&$userModel,$user, $password, $name, $email, $phone, $manager, $admin, $web, $movil, $userData) {
                $userModel = User::create([
                    'user' => $user,
                    'password' => Hash::make($password),
                    'name' => $name,
                    'email' => $email,
                    'phone' => $phone,
                    'user_type' => $manager,
                    'is_active' => 1,
                    'account_id' => $userData->account_id,
                    'created_by' => $userData->id
                ]);
                $userId = $userModel->id;
                if ($admin) PermissionsService ::setPermission($userId, 1);
                if ($web) PermissionsService::setPermission($userId, 2);
                if ($movil) PermissionsService::setPermission($userId, 3);
            });
            if ($userModel) {
                $userModel->permissions = $permissions;
            }        
            return $userModel;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), 1);
            
        }
    }

    public static function editUser($userId,$user, $name, $email, $phone, $manager, $admin, $web, $movil){
        try {
            $userModel = UserGetter::findUser($userId);
            $permissions = [];
            if ($admin) $permissions[] = 1;
            if ($web) $permissions[] = 2;
            if ($movil) $permissions[] = 3;
            DB::transaction(function() use (&$userModel,$userId, $user, $name, $email, $phone, $manager, $admin, $web, $movil) {
                // $userModel = 

                $userModel->user = $user;
                $userModel->name = $name;
                $userModel->email = $email;
                $userModel->phone = $phone;
                $userModel->user_type = (int) $manager;
                $userModel->save();
                $permissions = PermissionGetter::getPermmisionByUser($userId);
                foreach ($permissions as $p) {
                    if($p->permission_id == 1 && !$admin) PermissionsService::removePermissionToUser($userId, 1);
                    if($p->permission_id == 2 && !$web) PermissionsService::removePermissionToUser($userId, 2);
                    if($p->permission_id == 3 && !$movil) PermissionsService::removePermissionToUser($userId, 3);
                }

                if($admin){
                    if(!collect($permissions)->contains('permission_id', 1)){
                        PermissionsService::setPermission($userId, 1);
                    }
                }
                if ($web) {
                    if (!collect($permissions)->contains('permission_id', 2)) {
                        PermissionsService::setPermission($userId, 2);
                    }
                }
                if ($movil) {
                    if (!collect($permissions)->contains('permission_id', 3)) {
                        PermissionsService::setPermission($userId, 3);
                    }
                }
            });
            $userModel->permissions = $permissions;
            return $userModel;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), 1);
            
        }
    }

    public static function deleteUser($user){
        try {
            $currentUser = Auth::user()->id;
            if($currentUser == $user) throw new Exception("No puedes eliminar tu propio usuario", 1);
            
            PermissionsService::removePermissionToUser($user,1);
            PermissionsService::removePermissionToUser($user,2);
            PermissionsService::removePermissionToUser($user,3);
            $userModel = UserGetter::findUser($user);
            $userModel->is_active = false;
            $userModel->save();
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), 1);
            
        }
        
    }
}