<?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.startCurrent')))
            ->endDate(request('end', config('core.dashboard.endCurrent')))
            ->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($user, Impersonation $impersonation)
    {
        session()->put('impersonation.previous', url()->previous());

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

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

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

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

        return redirect('/');
    }
}
