<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, 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 {
      $result = '<script src="../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));

      $ch = \RequestOperations::getStandardCurl('https://api.friendlycaptcha.com/api/v1/siteverify', $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);
  }
}