<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Ignite\Core\Auth\Impersonation;
use Ignite\Core\Entities\User;
use Ignite\Core\Models\Dashboard\Dashboard;
use Ignite\Core\Http\Controllers\Controller;

class AdminController extends Controller
{

    /**
     * Show the admin index page.
     *
     * @param  Dashboard $dashboard
     * @return \Illuminate\View\View
     */
    public function index(Dashboard $dashboard)
    {
        return $dashboard->name(request('dashboard', config('core.dashboard.default')))
            ->autoLocate(config('core.dashboard.autolocate'))
            ->startDate(request('start', config('core.dashboard.start')))
            ->endDate(request('end', config('core.dashboard.end')))
            ->render('Core::admin.dashboard.index');
    }

    /**
     * Change Current User to User supplied
     *
     * @param  int $userId
     * @param  Impersonation $impersonation
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function mask($userId, Impersonation $impersonation)
    {
        session()->put('masquerade.previous', url()->previous());

        /** @var User $impersonator */
        $impersonator = auth()->user();
        $impersonated = User::findOrFail($userId);

        if ($impersonation->cannotImpersonate($impersonator, $impersonated)) {
            $this->flash('error', 'You are not authorized to masquerade as other users.');
            return redirect()->back();
        }

        $impersonation->startImpersonating($impersonator, $impersonated);

        $this->flash('success', "Masquerading as: {$impersonated->fullName()}");

        return redirect('/');
    }

    /**
     * Change Current User back to Login User
     *
     * @param  Impersonation $impersonation
     * @return \Illuminate\Http\RedirectResponse
     */
    public function unmask(Impersonation $impersonation)
    {
        if (! $impersonation->isImpersonating()) {
            return redirect(session()->pull('masquerade.previous', url()->previous()));
        }

        try {
            $user = $impersonation->stopImpersonating();
        } catch (\Exception $e) {
            $this->flash('error', $e->getMessage());
        }

        $this->flash('success', "Removed masquerade. Browsing as '{$user->fullName()}'\n");

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