<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Auth;

class ImpersonationController extends Controller
{
    /**
     * Admin starts impersonating a member. The admin's id is stashed in the
     * session so they can return. Guarded to admins only, and you cannot
     * impersonate yourself or another admin.
     */
    public function start(User $user)
    {
        $actor = Auth::user();

        abort_unless($actor && $actor->hasRole('admin'), 403);
        abort_if(session()->has('impersonator_id'), 403, 'Already impersonating.');
        abort_if($user->is($actor), 403, 'You cannot impersonate yourself.');
        abort_if($user->hasRole('admin'), 403, 'You cannot impersonate another admin.');

        session(['impersonator_id' => $actor->id]);
        Auth::login($user);

        return redirect()->route('dashboard')
            ->with('status', 'You are now viewing the site as '.$user->name.'.');
    }

    /**
     * Return to the original admin account.
     */
    public function leave()
    {
        $impersonatorId = session()->pull('impersonator_id');

        abort_unless($impersonatorId, 403);

        Auth::loginUsingId($impersonatorId);

        return redirect('/admin/users')
            ->with('status', 'Welcome back, you are yourself again.');
    }
}
