<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Http\Client; // <-- added

/**
 * ContactSubmissions Controller
 *
 * @property \App\Model\Table\ContactSubmissionsTable $ContactSubmissions
 */
class ContactSubmissionsController extends AppController
{
    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {
        $query = $this->ContactSubmissions->find()
            ->contain(['Users']);
        $contactSubmissions = $this->paginate($query);

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

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

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $contactSubmission = $this->ContactSubmissions->newEmptyEntity();

        if ($this->request->is('post')) {
            // --- reCAPTCHA verification ---
            $captchaResponse = (string)($this->request->getData('g-recaptcha-response') ?? '');
            $secret = '6Lf8o8UrAAAAAA3qxZHCfFsUyHEjtyZtO08W35lH'; // your secret key

            $captchaOk = false;
            if ($captchaResponse !== '' && $secret !== '') {
                $http = new Client(['ssl_verify_peer' => true]);
                $resp = $http->post(
                    'https://www.google.com/recaptcha/api/siteverify',
                    [
                        'secret'   => $secret,
                        'response' => $captchaResponse,
                        'remoteip' => $this->request->clientIp(),
                    ]
                );

                if ($resp->isOk()) {
                    $json = (array)$resp->getJson();
                    $captchaOk = !empty($json['success']);
                }
            }

            if (!$captchaOk) {
                $this->Flash->error(__('Please tick the reCAPTCHA checkbox (I\'m not a robot).'));
            } else {
                // Proceed to save only if captcha passed
                $contactSubmission = $this->ContactSubmissions->patchEntity($contactSubmission, $this->request->getData());
                if ($this->ContactSubmissions->save($contactSubmission)) {
                    $this->Flash->success(__('The contact submission has been saved.'));

                    return $this->redirect(['controller' => 'Pages', 'action' => 'home']);
                }
                $this->Flash->error(__('The contact submission could not be saved. Please, try again.'));
            }
        }

        $users = $this->ContactSubmissions->Users->find('list', limit: 200)->all();
        $this->set(compact('contactSubmission', 'users'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Contact Submission 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)
    {
        $contactSubmission = $this->ContactSubmissions->get($id, contain: []);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $contactSubmission = $this->ContactSubmissions->patchEntity($contactSubmission, $this->request->getData());
            if ($this->ContactSubmissions->save($contactSubmission)) {
                $this->Flash->success(__('The contact submission has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The contact submission could not be saved. Please, try again.'));
        }
        $users = $this->ContactSubmissions->Users->find('list', limit: 200)->all();
        $this->set(compact('contactSubmission', 'users'));
    }

    /**
     * Delete method
     *
     * @param string|null $id Contact Submission 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']);
        $contactSubmission = $this->ContactSubmissions->get($id);
        if ($this->ContactSubmissions->delete($contactSubmission)) {
            $this->Flash->success(__('The contact submission has been deleted.'));
        } else {
            $this->Flash->error(__('The contact submission could not be deleted. Please, try again.'));
        }

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