<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Http\Response;
use Cake\Http\Client;
use Cake\Core\Configure;

class ContactController extends AppController
{
    public function submit(): ?Response
    {
        $this->request->allowMethod(['post']);

        $fullName = trim((string)$this->request->getData('full_name'));
        $email = trim((string)$this->request->getData('email'));
        $phone = trim((string)$this->request->getData('phone'));
        $subject = trim((string)$this->request->getData('subject'));
        $message = trim((string)$this->request->getData('message'));
        $token = $this->request->getData('cf-turnstile-response');

        if ($fullName === '' || $email === '' || $phone === '' || $subject === '' || $message === '') {
            $this->Flash->error('Please fill in all fields.');
            return $this->redirect($this->referer() ?? '/');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->Flash->error('Please enter a valid email address.');
            return $this->redirect($this->referer() ?? '/');
        }

        if (empty($token)) {
            $this->Flash->error('Please complete the CAPTCHA.');
            return $this->redirect($this->referer() ?? '/');
        }

        $http = new Client();

        $response = $http->post(
            'https://challenges.cloudflare.com/turnstile/v0/siteverify',
            [
                'secret' => Configure::read('Captcha.turnstile.secretKey'),
                'response' => $token,
                'remoteip' => $this->request->clientIp(),
            ]
        );

        if (!$response->isOk()) {
            $this->Flash->error('CAPTCHA verification failed. Please try again.');
            return $this->redirect($this->referer() ?? '/');
        }

        $result = $response->getJson();

        if (empty($result['success'])) {
            $this->Flash->error('CAPTCHA verification failed. Please try again.');
            return $this->redirect($this->referer() ?? '/');
        }

        $this->Flash->success('Thank you for your message. We will get back to you soon.');

        return $this->redirect($this->referer() ?? '/');
    }
}
