<?php

namespace Ignite\Core\Http\Controllers\Admin;

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

class AdminController extends Controller
{

    /**
     * Show the admin index page.
     *
     * @param  Manager $manager
     * @return \Illuminate\Http\Response
     */
    public function index(Manager $manager)
    {
        $types = $manager->locate()->map(function ($dashboard) {
            return collect($dashboard)->map(function ($charts) {
                return collect($charts)->map(function ($chart) {
                    return app(array_pull($chart, 'class'), ['attributes' => $chart]);
                });
            });
        });

        $dashboard = request('dashboard', $types->keys()->last());
        $dashboards = $types->keys()->toArray();
        $manager->addMany($types[$dashboard]->flatMap(function ($chart) {
            return $chart;
        }))->calculate();

        return view('Core::admin.dashboard.index', compact(
            'manager', 'dashboards', 'dashboard'
        ));
    }

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

        $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 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\Response
     */
    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()));
    }
}
