<?php

namespace Modules\API\Authenticate\Service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

final class CredentialsService
{

    /**
     * @var \PDO $pdo
     */
    protected $pdo;

    /**
     * @var array<mixed>|false $infoUser
     */
    private $infoUser;

    /**
     * @var string $clientID
     */
    private $clientID;

    /**
     * @var string $clientSecret
     */
    private $clientSecret;

    /**
     * @var string $grantType
     */
    protected $grantType;

    /**
     * @var bool $valide
     */
    private $valide;

    /**
     * @var \Modules\API\Authenticate\Repository\CredentialsRepository $credentialsRepository
     */
    private $credentialsRepository;

    /**
     * @var string $JWTKEY
     */
    private $JWTKEY;
    
    /**
     * __construct
     *
     * @param  \PDO $pdo
     * @param  string $clientID
     * @param  string $clientSecret
     * @param  string $JWTKEY
     * @param  string $grantType
     * @return void
     */
    public function __construct(\PDO $pdo, string $clientID, string $clientSecret, string $JWTKEY, string $grantType = 'password')
    {
        $this->pdo = $pdo;
        $this->clientID = $clientID;
        $this->clientSecret = $clientSecret;
        $this->grantType = $grantType;
        $this->credentialsRepository = new \Modules\API\Authenticate\Repository\CredentialsRepository($pdo);
        $this->JWTKEY = $JWTKEY;
    }
    
    /**
     * getInfoUser
     *
     * @return array<mixed>|false
     */
    public function getInfoUser()
    {
        
        $secretIDCrypte = $this->credentialsRepository->getSecretID();
        try {
            $tokenBDD = (array)JWT::decode($secretIDCrypte, new Key($this->JWTKEY, 'HS256'));
            if ($tokenBDD[0] == $this->clientSecret) {
                $this->infoUser = $this->credentialsRepository->getInfoUser($this->clientID, $secretIDCrypte);
            } else {
                $this->infoUser = false;
            }
        } catch (\Exception $e) {
            $this->infoUser = false;
        }
        $this->setValid();
        return $this->infoUser;
    }
    
    /**
     * getValid
     *
     * @return void
     */
    public function setValid()
    {
        ($this->infoUser !== false && $this->infoUser['nbrTuple']==2)?$this->valide = true:$this->valide = false;
    }
    
    /**
     * getValid
     *
     * @return bool
     */
    public function getValid() : bool
    {
        return $this->valide;
    }
}
