<html>

<head>
  <meta name="robots" content="noindex,nofollow">
  <title>Autorizare mfinante efactura</title>
</head>

<body onload="parseUrl()">

  <script>
    function getQueryString(url, field) {
      const reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
      const string = reg.exec(url);
      return string ? string[1] : null;
    };
    function parseUrl() {
      const currentUrl = document.location.href;
      const callbackUrl = getQueryString(currentUrl, 'issuer');
      if (callbackUrl) {
        sessionStorage.setItem('callbackUrl', decodeURIComponent(callbackUrl));
        const client_id = getQueryString(currentUrl, 'client_id');
        const redirect_url = decodeURIComponent(getQueryString(currentUrl, 'redirect_uri'));
        window.location.href = 'https://logincert.anaf.ro/anaf-oauth2/v1/authorize'
          + `?client_id=${client_id}&redirect_uri=${redirect_url}`
          + '&grant_type=authorization_code&response_type=code&token_content_type=jwt';

      } else {
        const callbackUrl = sessionStorage.getItem('callbackUrl');
        const errorCode = getQueryString(currentUrl, 'errorcode');
        const error = getQueryString(currentUrl, 'error');
        const code = getQueryString(currentUrl, 'code');

        if (!code) {
          const pre = document.createElement('p');
          pre.innerText = 'Momentan anaf refuza accesul, incercati mai tarziu!';
          pre.style.textAlign = "center";

          const p = document.createElement('p');
          p.innerText = errorCode || error || 'Eroare autentificare token!';
          p.style.textAlign = "center";
          
          document.body.appendChild(pre);
          document.body.appendChild(p);
        }

        if (window.opener.postMessage) {
          window.opener.postMessage(code || errorCode || error || 'Eroare autentificare token!', callbackUrl);
          //setTimeout(() => window.close(), 2000);
        } else {
          console.log('sending code ', code || errorCode || error || 'Eroare autentificare token!')
        }
      }
    }
  </script>

  <div style="text-align: center;">Autorizare anaf efactura token</div>

</body>

</html>