<?php
namespace App\Model\Entity;

use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;

/**
 * User Entity.
 *
 * @property int $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property bool $is_active
 * @property string $username
 * @property \Cake\I18n\Time $created
 * @property string $modified
 * @property int $role_id
 * @property \App\Model\Entity\Role $role
 * @property \App\Model\Entity\Log[] $log
 */
class User extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*'                   => true,
        'id'                  => false,
        'professionals'       => true,
        'areas_of_occupation' => true,
        'specialties'         => true,
        'privileges'          => true,
        'units'               => true,

    ];

    /**
     * Fields that are excluded from JSON an array versions of the entity.
     *
     * @var array
     */
    protected $_hidden = [
        'password',
    ];

    protected function _setPassword($password)
    {
        return (new DefaultPasswordHasher)->hash($password);
    }

    public function retornaPrivilegio($user_id, $unit_id)
    {
        $privilege_table = TableRegistry::get('Privileges');
        $privileges      = $privilege_table->find('all')
            ->innerJoinWith('UnitsUsers')
            ->where(['UnitsUsers.user_id' => $user_id, "UnitsUsers.unit_id" => $unit_id])
            ->group('Privileges.id');
        $name = '';
        foreach ($privileges as $key => $value) {
            if ($key > 0) {
                $name = $name . ", " . $value->name;
            } else {
                $name .= $value->name;
            }
        }
        return $name;
        //return $privileges;
    }

    public function retornaSetor($user_id, $unit_id)
    {
        $sector_table = TableRegistry::get('Sectors');
        $sectors      = $sector_table->find('all')
            ->innerJoinWith('Units.UnitsUsers')
            ->where(['UnitsUsers.user_id' => $user_id, "Sectors.unit_id" => $unit_id])
            ->group('Sectors.id');
        $name = '';
        foreach ($sectors as $key => $value) {
            if ($key > 0) {
                $name = $name . ", " . $value->name;
            } else {
                $name .= $value->name;
            }
        }
        return $name;
        //return $privileges;
    }
}
