<?php

namespace Ignite\Core\Repositories;

use Ignite\Core\Contracts\Repositories\UserRepository as UserRepositoryContract;
use Ignite\Core\Entities\User;

class UserRepository implements UserRepositoryContract
{
    /**
     * The scoped User query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return User::with(['groups', 'groups.permissions']);
    }

    /**
     * Find a user by primary key.
     *
     * @param  int $id
     *
     * @return \Ignite\Core\Entities\User
     */
    public function find($id)
    {
        return $this->query()->where('user_id', $id)->firstOrFail();
    }

    /**
     * Assign the provided groups to the given user.
     *
     * @param $id
     * @param array $groups
     *
     * @return \Ignite\Core\Entities\User
     */
    public function assignGroups($id, array $groups)
    {
        $user = $this->find($id);
        $user->groups()->sync($groups);
        $user->save();

        return $user;
    }

    /**
     * Activate a user.
     *
     * @param  int $id
     * @return \Ignite\Core\Entities\User
     */
    public function activate($id)
    {
        $user = $this->find($id);
        $user->update(['status' => User::STAT_ACTIVE]);

        return $user;
    }

    /**
     * Deactivate a user.
     *
     * @param  int $id
     * @return \Ignite\Core\Entities\User
     */
    public function deactivate($id)
    {
        $user = $this->find($id);
        $user->update(['status' => User::STAT_INACTIVE]);

        return $user;
    }
}
