<?php

namespace App\Traits;

use App\Models\User;
use Illuminate\Http\RedirectResponse;

trait Impersonator
{
// Method to start impersonating a user
    public function impersonate($user): void
    {
        if ($this->canImpersonate()) {
            session(['impersonator_user' => auth()->id()]);
            session(['impersonated_user' => $user->id]);
            auth()->loginUsingId(session('impersonated_user'),true);
        }
    }

    // Method to stop impersonating and return to the original user
    public function stopImpersonating(): void
    {
        session()->forget('impersonated_user');
        auth()->loginUsingId(session('impersonator_user'),true);
    }

    // Check if the current user can impersonate
    public function canImpersonate(): bool
    {
        // Implement your authorization logic here
        // For example, only administrators can impersonate
        return $this->hasAnyRole('developer','admin') || $this->hasAnyPermission('impersonate user');
    }

    // Check if the user is currently being impersonated
    public function isImpersonating(): bool
    {
        return session()->has('impersonated_user');
    }

    // Get the impersonated user
    public function getImpersonatedUser(): User|null
    {
        if ($this->isImpersonating()) {
            return User::find(session('impersonated_user'));
        }
        return null;
    }

    public function start(User $user): RedirectResponse
    {
        auth()->user()->impersonate($user);
        return redirect()->route('admin:home');
    }

    public function stop(): RedirectResponse
    {
        auth()->user()->stopImpersonating();
        return redirect()->back();
    }
}
