<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Http\Client;
use Cake\Http\Exception\ForbiddenException;

/**
 * ContactForm Controller
 *
 * @property \App\Model\Table\ContactFormTable $ContactForm
 */
class ContactFormController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Flash');
    }

    private function requireAdmin()
    {
        $user = $this->request->getSession()->read('Auth.User');
        if (empty($user) || empty($user->is_admin)) {
            $this->Flash->error('Access denied. Admins only.');
            return $this->redirect('/');
        }
        return null;
    }

    private function validateId($id)
    {
        if (!ctype_digit((string)$id)) {
            $this->Flash->error(__('Invalid contact ID.'));
            return false;
        }
        return true;
    }

    public function index()
    {
        $redirect = $this->requireAdmin();
        if ($redirect) return $redirect;
    
        $sort = $this->request->getQuery('sort') ?: 'created'; 
        $direction = $this->request->getQuery('direction') ?: 'asc'; 
    
        $query = $this->ContactForm->find();
    
        $category = $this->request->getQuery('category');
        if (!empty($category)) {
            $query->where(['categories' => $category]);
        }
    
        $replied = $this->request->getQuery('replied');
        if ($replied !== null && $replied !== '') {
            $query->where(['replied' => $replied]);
        }
    
        $query->order([$sort => $direction]);
    
        $contactForm = $this->paginate($query);
    
        $this->set(compact('contactForm'));
    }


    public function view($id = null)
    {
        $redirect = $this->requireAdmin();
        if ($redirect) return $redirect;

        if (!$this->validateId($id)) {
            return $this->redirect(['action' => 'index']);
        }

        $contactForm = $this->ContactForm->find()
            ->where(['id' => $id])
            ->first();

        if (!$contactForm) {
            $this->Flash->error(__('Contact not found.'));
            return $this->redirect(['action' => 'index']);
        }

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

    public function add()
    {
        $contactForm = $this->ContactForm->newEmptyEntity();
    
        if ($this->request->is('post')) {
            $recaptchaResponse = $this->request->getData('g-recaptcha-response');
            $contactForm = $this->ContactForm->patchEntity($contactForm, $this->request->getData());
    
            if (!$this->verifyRecaptcha($recaptchaResponse)) {
                $this->Flash->error(__('Please complete the reCAPTCHA before submitting the form.'));
                $this->set(compact('contactForm'));
                return;
            }
    
            $message = $this->request->getData('message');
            if (strlen($message) > 2000) {
                $this->Flash->error(__('Your message exceeds the 2000 character limit.'));
                $this->set(compact('contactForm'));
                return;
            }
    
            if ($this->ContactForm->save($contactForm)) {
                $this->Flash->success(__('Your message has been submitted successfully.'));
                return $this->redirect(['action' => 'add']);
            } else {
                $this->Flash->error(__('There was an error submitting your message. Please try again.'));
            }
        }
    
        $this->set(compact('contactForm'));
    }


    public function toggleReplied($id = null)
    {
        $redirect = $this->requireAdmin();
        if ($redirect) return $redirect;

        if (!$this->validateId($id)) {
            return $this->redirect(['action' => 'index']);
        }

        $contactForm = $this->ContactForm->find()
            ->where(['id' => $id])
            ->first();

        if (!$contactForm) {
            $this->Flash->error(__('Contact not found.'));
            return $this->redirect(['action' => 'index']);
        }

        if ($this->request->is(['post', 'patch', 'put'])) {
            $contactForm->replied = $this->request->getData('replied') ? true : false;
            if ($this->ContactForm->save($contactForm)) {
                $this->Flash->success(__('Replied status updated.'));
            } else {
                $this->Flash->error(__('Unable to update replied status.'));
            }
        }
        return $this->redirect(['action' => 'view', $id]);
    }

    public function edit($id = null)
    {
        $redirect = $this->requireAdmin();
        if ($redirect) return $redirect;

        if (!$this->validateId($id)) {
            return $this->redirect(['action' => 'index']);
        }

        $contactForm = $this->ContactForm->find()
            ->where(['id' => $id])
            ->first();

        if (!$contactForm) {
            $this->Flash->error(__('Contact not found.'));
            return $this->redirect(['action' => 'index']);
        }

        if ($this->request->is(['patch', 'post', 'put'])) {
            $contactForm = $this->ContactForm->patchEntity($contactForm, $this->request->getData());
            if ($this->ContactForm->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'));
    }

    public function delete($id = null)
    {
        $redirect = $this->requireAdmin();
        if ($redirect) return $redirect;

        if (!$this->validateId($id)) {
            return $this->redirect(['action' => 'index']);
        }

        $this->request->allowMethod(['post', 'delete']);
        $contactForm = $this->ContactForm->find()
            ->where(['id' => $id])
            ->first();

        if (!$contactForm) {
            $this->Flash->error(__('Contact not found.'));
            return $this->redirect(['action' => 'index']);
        }

        if ($this->ContactForm->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']);
    }

    private function verifyRecaptcha($recaptchaResponse)
    {
        if (empty($recaptchaResponse)) {
            return false;
        }

        $secretKey = '6LenGxorAAAAACExlCRgoqaYlAC3SG8oyVl0MEaF';
        $url = 'https://www.google.com/recaptcha/api/siteverify';

        $http = new Client();
        $response = $http->post($url, [
            'secret' => $secretKey,
            'response' => $recaptchaResponse
        ]);

        $result = json_decode($response->getStringBody(), true);
        return !empty($result['success']);
    }
}
