<?php
namespace Incoviba\common;

use Incoviba\Common\Alias\OldModel as Model;
use Incoviba\Common\Factory\Model as Factory;

/**
 * User with Privileges
 * @property int $id
 * @property string $name length=50
 * @property string $password
 */
class User extends Model
{
  public static $_table = 'users';

  public function password($password = null)
  {
    if ($password == null) {
      return false;
    }
    $this->password = \password_hash($password, \PASSWORD_BCRYPT);
  }
  protected $permissions = null;
  public function permissions()
  {
    if ($this->permissions == null) {
      $permissions = $this->hasMany(Permission::class, 'ext_id')->where('permissions.type', 1)->findMany();
      if ($permissions == false) {
        $permissions = [];
      }
      foreach ($this->roles() as $role) {
        $rp = $role->permissions();
        if ($rp !== false) {
          $permissions = array_merge($permissions, $rp);
        }
      }
      if (count($permissions) == 0) {
        $permissions = false;
      }
      $this->permissions = $permissions;
    }
  	return $this->permissions;
  }
  public function roles()
  {
  	return $this->hasManyThrough(Role::class, UserRole::class, 'user', 'role')->findMany();
  }
  public function hasAccess($route)
  {
  	foreach ($this->roles() as $role) {
      if ($role->hasAccess($route) === true) {
  			return true;
  		}
  	}

    $action = $route->getArgument('action');
    $action = (new Factory(Action::class))->where(['description' => $action])->find();
    if (!$action) {
      return false;
    }

    $data = [
      'type' => 1,
      'ext_id' => $this->id,
      'action_id' => $action->id,
      'status' => 1
    ];
    $permission = (new Factory(Permission::class))->where($data)->find();
    if ($permission !== false) {
      return true;
    }
    return false;
  }
  public function checkAccess($action_name)
  {
  	foreach ($this->roles() as $role) {
      if ($role->checkAccess($action_name) === true) {
      	return true;
  		}
  	}
    $action = (new Factory(Action::class))->where(['description' => $action_name])->find();

    $permission = (new Factory(Permission::class))->where([
      'type' => 1,
      'ext_id' => $this->id,
      'action_id' => $action->id,
      'status' => 1
    ])->find();
    if ($permission !== false) {
      return true;
    }
    return false;
  }
  public function hasRole($role)
  {
    foreach ($this->roles() as $r) {
      if ($r->description == $role or $r->id == $role) {
        return true;
      }
    }
    return false;
  }
}
