<?php

namespace App\PackagesAdmin\Manager\Models;

use App\Packages\Core\Traits\RepositoryTrait;
use App\PackagesAdmin\Manager\Repository\ManagerRepository;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;

/**
 * Class Manager
 * @package App\Models
 *
 * @property int $id
 * @property string $first_name
 * @property string $last_name
 * @property string $email
 * @property string $password
 * @property string $remember_token
 * @property boolean $is_active
 * @property integer $role_id
 *
 * @property string $created_at
 * @property string $updated_at
 *
 * @property-read ManagerRole $managerRole
 */
class Manager extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
	use Notifiable,
		Authenticatable,
		Authorizable,
		CanResetPassword,
		RepositoryTrait;

	const WEB_GUARD = 'web_managers';

	/** @var string */
	public static $repositoryClass = ManagerRepository::class;

	/** @var string */
	protected $table = 'table_manager';

	/**
	 * @return HasOne
	 */
	public function managerRole()
	{
		return $this->hasOne(ManagerRole::class, 'id', 'role_id');
	}

	public function canAccess($where)
    {
        if ( empty($this->role_id) ) return false;

        $check = $this->query()
            ->leftJoin(
                'table_manager_role',
                'table_manager_role.id',
                '=',
                'table_manager.role_id'
            )
            ->leftJoin(
                'table_manager_permission',
                'table_manager_permission.role_id',
                '=',
                'table_manager_role.id'
            )
            ->where('table_manager.id', $this->id)
            ->where('table_manager_permission.value', '=', $where)
            ->first();

        return ( $check ) ? true : false;
    }

    public function getAllPermissions()
    {
        if ( empty($this->role_id) ) return false;

        $permissions = ManagerPermission::repository()->getRolePermissions($this->role_id);

        return $permissions;
    }

}
