<?php
declare(strict_types=1);

namespace App\Controller;

/**
 * ContactForms Controller
 *
 * @property \App\Model\Table\ContactFormsTable $ContactForms
 */
class ContactFormsController extends AppController
{

       /**
     * Controller initialize override
     *
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();

        // By default, CakePHP will (sensibly) default to preventing users from accessing any actions on a controller.
        // These actions, however, are typically required for users who have not yet logged in.
        $this->Authentication->allowUnauthenticated(['add']);
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {
        $query = $this->ContactForms->find();
        $contactForms = $this->paginate($query);

        $this->set(compact('contactForms'));
    }

    /**
     * View method
     *
     * @param string|null $id Contact Form id.
     * @return \Cake\Http\Response|null|void Renders view
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $contactForm = $this->ContactForms->get($id, contain: []);
        $this->set(compact('contactForm'));
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {

        // Add into PHP validation to check the submitted captcha response is a success or fail

        /* Google ReCaptcha Verification */
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $privatekey = "6Lc6puEqAAAAANWK-58iGqs5XnvpoEYdmfWB6Ex1";

        $contactForm = $this->ContactForms->newEmptyEntity();
        if ($this->request->is('post')) {
        if (isset($this->request->getData()['g-recaptcha-response'])){ //Response is submitted
            //Check if it is valid
            $gCaptchaResponse = $this->request->getData()['g-recaptcha-response'];
            $response = file_get_contents($url."?secret=".$privatekey."&response=".$gCaptchaResponse);
            $data = json_decode($response);

            if($data->success) { //Valid response
                    $contactForm = $this->ContactForms->patchEntity($contactForm, $this->request->getData());
                    if ($this->ContactForms->save($contactForm)) {
                        $this->Flash->success(__('We have received your contact form and will be in touch shortly!'));
        
                        return $this->redirect(['action' => 'add']);
                    
                    $this->Flash->error(__('The contact form could not be saved. Please, try again.'));
                }
            } else { //Invalid response
                $this->Flash->error(__('Your captcha response has failed, please refresh or reattempt the recaptcha.'));

            }
            //."&remoteip=".$_SERVER['REMOTE_ADDR']


        } else { //Hasnt attempted captcha yet
            $this->Flash->error(__('Please complete the captcha response!'));

        }
    }
        $this->set(compact('contactForm'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Contact Form id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $contactForm = $this->ContactForms->get($id, contain: []);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $contactForm = $this->ContactForms->patchEntity($contactForm, $this->request->getData());
            if ($this->ContactForms->save($contactForm)) {
                $this->Flash->success(__('The contact form has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The contact form could not be saved. Please, try again.'));
        }
        $this->set(compact('contactForm'));
    }

    /**
     * Delete method
     *
     * @param string|null $id Contact Form id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $contactForm = $this->ContactForms->get($id);
        if ($this->ContactForms->delete($contactForm)) {
            $this->Flash->success(__('The contact form has been deleted.'));
        } else {
            $this->Flash->error(__('The contact form could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}
