<?php

namespace App\Core\Auth\Classes;

use ORM\Entity as Entity;
use App\Core\Auth\Classes\Group as Group;
use App\Core\Auth\Classes\Permission as Permission;
use ORM\DBInstance;

class User extends Entity{

    public $method = 'manual';
    public $username = '';
    public $name = '';
    public $email = '';
    public $password = '';

    const _tableName  = "auth_user";
    const _timestamps = true;
    const _softdelete = true;

    function groups(){
        return $this->belongsToMany(Group::class, 'auth_group_user', 'user_id', 'group_id')->get();
    }

    function specificPermissions(){
        return $this->belongsToManyExtended(Permission::class, 'auth_permission_user', 'user_id', 'permission_id');
    }

    function permissions(){
        $permissions = [];

        foreach ($this->groups() as $group){
            foreach ($group->permissions()->get() as $permission){
                $permissions[] = $permission->name;
            }
        }

        foreach ($this->specificPermissions()->get() as $permission){
            if($permission->action == 'a'){
                $permissions[] = $permission->childElement->name;
            }else{

            }
        }

        return $permissions;

    }

    function groupsoptions(){
        $groupList = Group::findAll()->get();

        foreach($this->groups() as $group){
            foreach($groupList as $key => $list){
                if($group->id == $list->id){
                    $groupList[$key]->selected = true;
                }
            }
        }

        return $groupList;
    }

    public function appendGroups($groups){

        DBInstance::execute('DELETE FROM {auth_group_user} WHERE user_id = ?', [$this->id]);

        foreach($groups as $group){
            DBInstance::insertRecord('auth_group_user', ['user_id' => $this->id, 'group_id' => $group]);
        }
    }

}