<?php

namespace App\Http\Controllers\Admin;

use App\Facade\Theme;
use App\Facade\UserConfig;
use App\Group;
use App\Helpers\PermissionsHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        View::share('is_admin', true);
    }

    public function delete(Request $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $user = User::where('id', intval($id))->first();
        if (is_null($user))
        {
            App::abort(404);
        }

        if ($user->id == Auth::user()->id)
        {
            $request->session()->flash('warning', trans('admin.cannot_delete_own_user_account'));
            return redirect(route('users.index'));
        }

        return Theme::render('admin.delete_user', ['user' => $user]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $users = User::orderBy('name')
            ->paginate(UserConfig::get('items_per_page'));

        return Theme::render('admin.list_users', [
            'error' => $request->session()->get('error'),
            'success' => $request->session()->get('success'),
            'users' => $users,
            'warning' => $request->session()->get('warning')
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        return Theme::render('admin.create_user');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Requests\StoreUserRequest $request)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $user = new User();
        $user->fill($request->only(['name', 'email', 'password']));
        $user->password = bcrypt($user->password);
        $user->is_activated = true;
        $user->is_admin = (strtolower($request->get('is_admin')) == 'on');
        $user->enable_profile_page = UserConfig::get('social_user_profiles');
        $user->save();

        return redirect(route('users.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $user = User::where('id', intval($id))->first();
        if (is_null($user))
        {
            App::abort(404);
        }

        $groups = Group::orderBy('name')->get();
        $usersGroups = [];
        foreach ($user->groups()->get() as $group)
        {
            $usersGroups[] = $group->id;
        }

        if (!$request->session()->has('_old_input'))
        {
            $request->session()->flash('_old_input', $user->toArray());
        }

        return Theme::render('admin.edit_user', ['user' => $user, 'groups' => $groups, 'users_groups' => $usersGroups]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Requests\StoreUserRequest $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $user = User::where('id', intval($id))->first();
        if (is_null($user))
        {
            App::abort(404);
        }

        $user->fill($request->only(['name', 'email']));

        // Change user's password only if supplied
        if (strlen($request->get('password')) > 0)
        {
            $user->password = bcrypt($request->get('password'));
        }

        // Prevent the current administrator from removing their admin rights
        if (
            $user->is_admin &&
            $user->id == Auth::user()->id &&
            strtolower($request->get('is_admin')) != 'on'
        ) {
            $request->session()->flash('warning', trans('admin.cannot_remove_own_admin'));
        }
        else
        {
            $user->is_admin = (strtolower($request->get('is_admin')) == 'on');
        }

        // Manually activate account if requested
        if (strtolower($request->get('is_activated')) == 'on')
        {
            $user->is_activated = true;
            $user->activation_token = null;
        }

        // Sync the group memberships
        $data = $request->all();
        $syncData = [];

        if (isset($data['user_group_id']))
        {
            foreach ($data['user_group_id'] as $groupID)
            {
                $syncData[$groupID] = ['created_at' => new \DateTime(), 'updated_at' => new \DateTime()];
            }

            $user->groups()->sync($syncData);
        }
        else
        {
            $user->groups()->detach();
        }

        $user->save();

        // Rebuild the permissions cache
        $helper = new PermissionsHelper();
        $helper->rebuildCache();

        return redirect(route('users.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        /** @var User $user */
        $user = User::where('id', intval($id))->first();
        if (is_null($user))
        {
            App::abort(404);
        }

        if ($user->id == Auth::user()->id)
        {
            $request->session()->flash('warning', trans('admin.cannot_delete_own_user_account'));
            return redirect(route('users.index'));
        }

        try
        {
            $user->delete();
            $request->session()->flash('success', trans('admin.user_deletion_successful', [
                'name' => $user->name
            ]));
        }
        catch (\Exception $ex)
        {
            $request->session()->flash('error', trans('admin.user_deletion_failed', [
                'error_message' => $ex->getMessage(),
                'name' => $user->name
            ]));
        }

        return redirect(route('users.index'));
    }

    /**
     * Returns a list of users in JSON format - either all users or users matching the "q" query string parameter
     *
     * @param  string  $q Search term
     * @return \Illuminate\Http\Response
     */
    public function searchJson(Request $request)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-users');

        $limit = intval($request->get('n'));
        if ($limit == 0)
        {
            $limit = 100;
        }

        $q = $request->get('q');
        if (strlen($q) == 0)
        {
            return User::limit($limit)->get()->toJson();
        }

        return User::where('name', 'like', '%' . $q . '%')
            ->limit($limit)
            ->orderBy('name')
            ->get()
            ->toJson();
    }
}