<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Captchas;


class FriendlyCaptcha implements Captcha
{
  public function getCaptcha($pNoBr = false, $pVorbelegung = '', $pPrefix = 'tedit')
  {
    $settings = \ToolSettingsAPI::getToolSettings(4);
    $key = $settings->friendlyCaptchaSiteKey;
    if ($key == '') {
      \Logger::logg('Es fehlt der für FriendlyCaptcha nötige Schlüssel im Webadmin (Einstellungen/Layout/Warenkorb/Anmeldeverfahren-Captchas) '
        . '- bitte ggf. unter https://friendlycaptcha.com/de/ besorgen und hinterlegen', 50);
      $result = '<div class="friendlycaptcha-error">Ungültige FriendlyCaptcha Hinterlegung, Debugnachricht geschrieben.</div>';
    } else {
      
      
      if ($settings->friendlyCaptchaEndpoint == 'Eu') {
        $result = '<script src="' . \CmsAnb::getAnbindung()->getKuferWebUrl() . 'extern/friendlycaptcha/widget.min.js?v=0.9.5" async defer></script>
          <div class="frc-captcha" data-sitekey="' . $key . '" data-lang="de" 
          data-puzzle-endpoint="https://eu-api.friendlycaptcha.eu/api/v1/puzzle,https://api.friendlycaptcha.com/api/v1/puzzle"></div>';
      } else {
        $result = '<script src="' . \CmsAnb::getAnbindung()->getKuferWebUrl() . 'extern/friendlycaptcha/widget.min.js?v=0.9.5" async defer></script>
          <div class="frc-captcha" data-sitekey="' . $key . '" data-lang="de"></div>';
      }
    }

    return $result;
  }

  public function isValid($pObject = null, $pValidateFromPost = false, $pPrefix = 'tedit', $pForceWbPrefix = false)
  {
    $settings = \ToolSettingsAPI::getToolSettings(4);
    $key = $settings->friendlyCaptchaSiteKey;
    $secret = $settings->friendlyCaptchaSecret;
    if ($key == '' || $secret == '') {
      return false;
    }

    if (\PostOperations::isDefined('frc-captcha-solution')) {
      $postfields = \http_build_query(array(
        'solution' => \PostOperations::getVarValue('frc-captcha-solution'),
        'secret' => $secret,
        'sitekey' => $key));

      $siteverifyurl = 'https://api.friendlycaptcha.com/api/v1/siteverify';

      if ($settings->friendlyCaptchaEndpoint = 'Eu') {
        $siteverifyurl = 'https://eu-api.friendlycaptcha.eu/api/v1/siteverify';
      }
      $ch = \RequestOperations::getStandardCurl($siteverifyurl, $postfields);
      $content = curl_exec($ch);
      curl_close($ch);

      if (\json_decode($content)->success) {
        \SessionOperations::setVarValueIntern('captcha_value', true);
      } else {
        \SessionOperations::setVarValueIntern('captcha_value', false);
      }
    }

    return \SessionOperations::getVarValueIntern('captcha_value', false);
  }
}