<?php

namespace Ignite\Core\Http\Controllers\Admin;

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

class AdminController extends Controller
{
    /**
     * Show the admin index page.
     *
     * @param  Dashboard $dashboard
     * @return \Illuminate\View\View
     */
    public function index(Dashboard $dashboard)
    {
        $defaultStart = today()->subDays(config('core.dashboard.startCurrentOffsetDays', 7));
        $defaultEnd = today()->subDays(config('core.dashboard.endCurrentOffsetDays', 0));
        $start = $defaultStart->format('Y-m-d');
        $end = $defaultEnd->format('Y-m-d');

        if ('range' == config('core.dashboard.comparison')) {
            $start = Carbon::parse(request()->query('current-start', $defaultStart))->format('Y-m-d');
            $end = Carbon::parse(request()->query('current-end', $defaultEnd))->format('Y-m-d');
        }

        return $dashboard->name(request('dashboard', config('core.dashboard.default')))
            ->autoLocate(config('core.dashboard.autolocate'))
            ->startDate(request('start', $start))
            ->endDate(request('end', $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($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('/');
    }
}
