<?php
namespace App\Controllers\Seller;

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

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

class SellerAuth extends Container
{
  public function login(Request $request, Response $response, $args){
    //$hash seller teste = 'Convicto@seller2019';
    //$hash seller outro= 'Seller@2019convicto';

    $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\Seller\UserSeller');
    $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' => 'Seller System Convicto Club',
      'email' => $email,
      'reg' => $bs
    ];

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

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

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