<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Core\Configure;
use Cake\Http\Client;
use Cake\Http\Exception\NotFoundException;


class LandingPageController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->Authentication->allowUnauthenticated(['view', 'index','restrictedCargos','terms']);
    }

    public function index()
    {
        $contactMessagesTable = $this->fetchTable('ContactMessages');

        $landingContactMessage = $contactMessagesTable->newEmptyEntity();
        $landingSuccessMessage = null;
        $landingSubmittedSuccessfully = false;
        $landingSaveErrorMessage = null;

        if ($this->request->is('post') && $this->request->getData('form_source') === 'landing_contact') {
            $data = $this->request->getData();

            if (isset($data['phone'])) {
                $data['phone'] = preg_replace('/\D+/', '', (string)$data['phone']);
            }

            if (isset($data['email'])) {
                $data['email'] = trim((string)$data['email']);
            }

            $recaptchaResponse = (string)$this->request->getData('g-recaptcha-response');

            if (empty($recaptchaResponse)) {
                $landingContactMessage->setError('g-recaptcha-response', ['Please complete the CAPTCHA.']);
            } else {
                $http = new Client(['timeout' => 10]);
                $secret = (string)Configure::read('Recaptcha.secret');

                $response = $http->post(
                    'https://www.google.com/recaptcha/api/siteverify',
                    [
                        'secret' => $secret,
                        'response' => $recaptchaResponse,
                    ]
                );

                $result = (array)json_decode((string)$response->getStringBody(), true);

                if (empty($result['success'])) {
                    $landingContactMessage->setError('g-recaptcha-response', ['CAPTCHA failed. Please try again.']);
                }
            }

            $landingContactMessage = $contactMessagesTable->patchEntity($landingContactMessage, $data);

            if ($landingContactMessage->getErrors()) {
                $landingSaveErrorMessage = 'Please check the required fields and try again.';
            } else {
                if ($contactMessagesTable->save($landingContactMessage)) {
                    $landingSuccessMessage = 'Your message has been sent successfully. We will get in touch with you soon.';
                    $landingSubmittedSuccessfully = true;
                    $landingContactMessage = $contactMessagesTable->newEmptyEntity();
                } else {
                    $landingSaveErrorMessage = 'The form was submitted, but the message could not be saved to the database.';
                }
            }
        }

        $this->set(compact(
            'landingContactMessage',
            'landingSuccessMessage',
            'landingSubmittedSuccessfully',
            'landingSaveErrorMessage'
        ));
    }
    public function restrictedCargos()
    {
    }

    public function terms()
    {
    }
}
