<?php

namespace Ignite\Core\Traits;

use Ignite\Core\Auth\Impersonation;

trait StopImpersonating
{
    /**
     * If user is impersonating. Stop impersonating and redirect back to where they were.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function stopImpersonating()
    {
        /** @var Impersonation $impersonation */
        $impersonation = app(Impersonation::class);

        if ($impersonation->isImpersonating()) {
            try {
                $user = $impersonation->stopImpersonating();
                $this->flash('success', "Exited impersonation. Browsing as '{$user->fullName()}'\n");
            } catch (\Exception $e) {
                $this->flash('error', $e->getMessage());
            }

            return redirect(session()->pull('impersonation.previous', url()->previous()));
        }

        return null;
    }
}
