<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        //LEFT JOIN location_proyect
        $this->hasMany('Video',[
            'foreignKey' => 'id_usuario']);
        $this->hasMany('CatCategoria',[
            'foreignKey' => 'id_usuario']);
        $this->hasMany('CatSubategoria',[
            'foreignKey' => 'id_usuario']);
        $this->hasMany('CatSerie',[
            'foreignKey' => 'id_usuario']);
        $this->belongsTo('CatRoles',[
            'foreignKey' => 'role']);
        $this->belongsTo('CatStatusUser',[
            'foreignKey' => 'estatus']);
    }
    public function validationDefault(Validator $validator)
    {
        return $validator
            ->notEmpty('username', 'A username is required')
            ->notEmpty('password', 'A password is required')
            ->notEmpty('role', 'A role is required')
            ->notEmpty('confirm_password' , 'Repeat the password')
            ->notEmpty('new_password' , 'Repeat the password')
            ->add('role', 'inList', [
                'rule' => ['inList', ['1', '2']],
                'message' => 'Please enter a valid role'
            ])
            ->add('confirm_password', 'no-misspelling', [
                'rule' => ['compareWith', 'password'],
                'message' => 'Passwords are not equal',
            ])
            ->add('new_password', 'no-misspelling', [
                'rule' => ['compareWith', 'confirm_password'],
                'message' => 'Passwords are not equal',
            ])
            ->add('email', 'valid-email', ['rule' => 'email']);
    }
    function getRoles()
    {
        $CatRolesTAble=TableRegistry::get("CatRoles");
        $roles=$CatRolesTAble->find("all")->where(["estatus"=>1]);
        return json_encode($roles, JSON_PRETTY_PRINT);
    }
    function GetAllUsers()
    {
        $UsersTAble=TableRegistry::get("Users");
        $users=$UsersTAble->find("all")->toArray();
        return json_encode($users, JSON_PRETTY_PRINT);
    }
    function deleteUser($data)
    {
        $UsersTable = TableRegistry::get('Users');
        $UsersTable->deleteAll(['id'=>$data["user"]]);
    }
    function statusUser($data)
    {
        $status=1;
        if($data["status"]==1)
        {
            $status=2;
        }
        $UsersTable = TableRegistry::get('Users');
        $User=$UsersTable->newEntity();
        $User=$UsersTable->get($data["user"]);
        $User->estatus=$status;
        $UsersTable->save($User);
    }
}

?>