<?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()
    {
        $this->paginate = [
            'order' => ['ContactForms.created' => 'desc'],
        ];

        $query = $this->ContactForms->find();

        $firstName = $this->request->getQuery('first_name');
        $lastName = $this->request->getQuery('last_name');
        $email = $this->request->getQuery('email');
        $dateFrom = $this->request->getQuery('date_from');
        $dateTo = $this->request->getQuery('date_to');

        if (!empty($firstName)) {
            $query->where(['ContactForms.first_name LIKE' => "%$firstName%"]);
        }

        if (!empty($lastName)) {
            $query->where(['ContactForms.last_name LIKE' => "%$lastName%"]);
        }

        if (!empty($email)) {
            $query->where(['ContactForms.email LIKE' => "%$email%"]);
        }

        if (!empty($dateFrom)) {
            $query->where(['ContactForms.created >=' => $dateFrom . ' 00:00:00']);
        }

        if (!empty($dateTo)) {
            $query->where(['ContactForms.created <=' => $dateTo . ' 23:59:59']);
        }

        $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 = "6LcEYhYrAAAAAD8QLzXUGEkW-VqsaUQr89Gl3XTE";
            //"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(['controller' => 'Pages', 'action' => 'display', 'home']);

                    $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']);
    }

    public function updateStatus(?string $id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $contactForm = $this->ContactForms->get($id);

        // Flip the replied field value (should be a boolean)
        $contactForm->replied = !$contactForm->replied;

        if ($this->ContactForms->save($contactForm)) {
            $this->Flash->success(__('Enquiry status has been updated.'));
        } else {
            $this->Flash->error(__('Enquiry status could not be updated. Please try again.'));
        }

        // Instead of redirect to index page, redirect to where the user came from
        return $this->redirect($this->referer());
    }

}
