<?php 
 
namespace App\Controller; 
 
use App\Entity\Newsletter; 
use App\Form\Type\NewsletterType; 
use Doctrine\DBAL\Exception; 
use Doctrine\Persistence\ManagerRegistry; 
use phpDocumentor\Reflection\Types\Mixed_; 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener; 
use Symfony\Component\Routing\Annotation\Route; 
 
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient; 
use Google\Cloud\RecaptchaEnterprise\V1\Event; 
use Google\Cloud\RecaptchaEnterprise\V1\Assessment; 
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason; 
 
class HomeController extends AbstractController 
{ 
    /** 
     * @var ParameterBagInterface 
     */ 
    private $params; 
 
    public function __construct(ParameterBagInterface $params) 
    { 
        $this->params = $params; 
    } 
 
    /** 
     * @Route("/", name="index") 
     * @param Request $request 
     * @return Response 
     */ 
    public function index(Request $request): Response 
    { 
        $page = $request->get('page', null); 
        if($page === 'beta') { 
            return $this->render('home/beta.html.twig', [ 
            ]); 
        } else { 
 
            // creates a task object and initializes some data for this example 
            $newsletter = new Newsletter(); 
 
            $form = $this->createForm(NewsletterType::class, $newsletter, [ 
                'action' => $this->generateUrl('thank_you'), 
                'method' => 'POST' 
            ]); 
 
            $response = $this->render('home/index.html.twig', [ 
                'form' => $form->createView() 
            ]); 
 
            $response->setPublic(); 
            $response->setMaxAge(2500000); 
 
            $response->headers->addCacheControlDirective('must-revalidate', true); 
 
            $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true'); 
 
            return $response; 
        } 
    } 
 
    /** 
     * @Route("/trading-strategy-algorithm-that-will-work-at-any-time", name="trading_strategy_text") 
     */ 
    public function tradingStrategyText(): Response 
    { 
 
        return $this->render('home/trading-strategy-text.html.twig', [ 
        ]); 
    } 
 
    /** 
     * @Route("/privacy-policy", name="privacy_policy") 
     */ 
    public function privacyPolicy(): Response 
    { 
 
        return $this->render('home/privacy-policy.html.twig', [ 
        ]); 
    } 
 
    /** 
     * @Route("/thank-you", name="thank_you") 
     * @param Request $request 
     * @param ManagerRegistry $registry 
     * @return Response 
     */ 
    public function thankYou(Request $request, ManagerRegistry $registry): Response 
    { 
        $error = false; 
        $duplicate = false; 
 
        // just set up a fresh $task object (remove the example data) 
        $newsletter = new Newsletter(); 
 
        $form = $this->createForm(NewsletterType::class, $newsletter); 
 
        $form->handleRequest($request); 
        if ($form->isSubmitted() && $form->isValid()) { 
            // $form->getData() holds the submitted values 
            // but, the original `$task` variable has also been updated 
            $newsletter = $form->getData(); 
            $newsletter->setCreatedAt(new \DateTimeImmutable('now')); 
            $newsletter->setIp($_SERVER['REMOTE_ADDR']); 
 
//            dump($newsletter); 
            $recaptcha_response = $request->get('g-recaptcha-response'); 
//            dump($recaptcha_response); 
 
//            $score = $this->create_assessment( 
//                '6LeRJt0eAAAAAMYqufqaweCRDb0fDBLm_ub20maZ', 
//                $recaptcha_response, 
//                'ntnewsletter' 
//            ); 
 
//            dump('This is score in TY controller', $score); 
 
            try { 
                $entityManager = $registry->getManager(); 
                $entityManager->persist($newsletter); 
                $entityManager->flush(); 
 
            } catch (Exception\UniqueConstraintViolationException $exception) { 
//                dump($exception); 
                $duplicate = true; 
            } catch (\Exception $exception) { 
                $error = true; 
            } 
 
            return $this->render('home/thank-you.html.twig', [ 
                'form' => $form, 
                'error' => $error, 
                'duplicate' => $duplicate 
            ]); 
 
        } else { 
            return $this->redirectToRoute('index'); 
        } 
 
    } 
 
 
 
    /** 
     * Create an assessment to analyze the risk of a UI action. 
     * @param string $siteKey The key ID for the reCAPTCHA key (See https://cloud.google.com/recaptcha-enterprise/docs/create-key) 
     * @param string $token The user's response token for which you want to receive a reCAPTCHA score. (See https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#retrieve_token) 
     * @param string $project Your Google Cloud project ID 
     * @return null|mixed 
     */ 
    function create_assessment(string $siteKey, string $token, string $project) { 
 
        $score = null; 
 
        // TODO: To avoid memory issues, move this client generation outside 
        // of this example, and cache it (recommended) or call client.close() 
        // before exiting this method. 
        $client = new RecaptchaEnterpriseServiceClient(); 
        $projectName = $client->projectName($project); 
 
        $event = (new Event()) 
            ->setSiteKey($siteKey) 
            ->setToken($token); 
 
        $assessment = (new Assessment()) 
            ->setEvent($event); 
 
 
        try { 
            $response = $client->createAssessment( 
                $projectName, 
                $assessment 
            ); 
 
            // You can use the score only if the assessment is valid, 
            // In case of failures like re-submitting the same token, getValid() will return false 
            if ($response->getTokenProperties()->getValid() == false) { 
                dump('The CreateAssessment() call failed because the token was invalid for the following reason: '); 
                dump(InvalidReason::name($response->getTokenProperties()->getInvalidReason())); 
            } else { 
                dump('The score for the protection action is:'); 
                $score = $response->getRiskAnalysis()->getScore(); 
 
                // Optional: You can use the following methods to get more data about the token 
                // Action name provided at token generation. 
                // printf($response->getTokenProperties()->getAction() . PHP_EOL); 
                // The timestamp corresponding to the generation of the token. 
                // printf($response->getTokenProperties()->getCreateTime()->getSeconds() . PHP_EOL); 
                // The hostname of the page on which the token was generated. 
                // printf($response->getTokenProperties()->getHostname() . PHP_EOL); 
            } 
        } catch (\Exception $e) { 
            dump('CreateAssessment() call failed with the following error: '); 
            dump($e); 
        } 
 
        return $score; 
    } 
}