<?php
namespace App\Controllers\Admin;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

use \App\Controllers\Container;
use Firebase\JWT\JWT;

class Auth extends Container
{
  public function auth(Request $request, Response $response, $args){
    $pass = password_hash("teste", PASSWORD_DEFAULT);
    var_dump($pass);


    $params = (object) $request->getParams();
    $nameUser = $request->getParam('name');
    $email = $request->getParam('email');
    $password = $request->getParam('password');

    $entityManager = $this->container->get('em');
    $userRepository = $entityManager->getRepository('App\Models\Entity\Admin\User');
    $user = $userRepository->findAll();

    foreach ($user as $key => $u) {
      if ($email == $u->getEmail()) {
        $idUser = $u->getId();
      }
    }

    if (empty($idUser)) {
      throw new \Exception("Usuario nao cadastrado", 401);
    }

    $seller = $userRepository->find($idUser);

    if ($seller->getNameUser() != $nameUser) {
      throw new \Exception("Usuario invalido", 401);
    }

    if (!password_verify($password, $seller->getPassword())) {
      throw new \Exception("Senha invalida", 401);
    }

    $bs = bin2hex(random_bytes(16));

    $tkPayload = [
      'name' => 'Admin Convicto Club System',
      'email' => $email,
      'reg' => $bs
    ];

    $keyToken = getenv('jwt_key');
    $nameUser = $seller->getNameUser();

    $token = JWT::encode($tkPayload, $keyToken);

    return $response->withHeader('X-ACCESS-TOKEN', $token)->withJson($nameUser,200);
  }
}
