<?php
declare(strict_types=1);

namespace App\Controller;

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

/**
 * @property \App\Model\Table\ContactMessagesTable $ContactMessages
 */
class ContactController extends AppController
{
    public function beforeFilter(EventInterface $event)
    {
        parent::beforeFilter($event);

        $this->Authentication->addUnauthenticatedActions(['index']);
    }
    private function isAdminOrStaff(): bool
    {
        $id = $this->request->getAttribute('identity');
        return (bool)($id && in_array($id->get('role'), ['admin', 'staff'], true));
    }

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

        $contactMessage = $contactMessagesTable->newEmptyEntity();
        $successMessage = null;
        $submittedSuccessfully = false;

        if ($this->request->is('post')) {
            $contactMessage = $contactMessagesTable->patchEntity(
                $contactMessage,
                $this->request->getData()
            );

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

            if (empty($recaptchaResponse)) {
                $contactMessage->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'])) {
                    $contactMessage->setError('g-recaptcha-response', ['CAPTCHA failed. Please try again.']);
                }
            }

            if (!$contactMessage->getErrors()) {
                if ($contactMessagesTable->save($contactMessage)) {
                    $successMessage = 'Your message has been sent successfully. We will get in touch with you soon. Refresh this page if you want to send more messages.';
                    $submittedSuccessfully = true;

                    $contactMessage = $contactMessagesTable->newEmptyEntity();
                }
            }
        }

        $this->set(compact('contactMessage', 'successMessage', 'submittedSuccessfully'));
    }
        public function allMessages()
    {
        if (!$this->isAdminOrStaff()) {
            throw new \Cake\Http\Exception\ForbiddenException('Staffs only.');
        }
        $this->viewBuilder()
            ->setLayout('admin')
            ->setLayoutPath('Admin');

        $contactMessagesTable = $this->fetchTable('ContactMessages');

        $query = $contactMessagesTable->find()
            ->orderBy([
                'is_read' => 'ASC',
                'created' => 'DESC'
            ]);

        $contactMessages = $this->paginate($query);

        $allMessages = $contactMessagesTable->find()
            ->orderBy([
                'is_read' => 'ASC',
                'created' => 'DESC'
            ])
            ->all();

        $this->set(compact('contactMessages', 'allMessages'));

        return $this->render('/Admin/Dashboard/all_messages');
    }

    public function markAsRead($id = null)
    {
        if (!$this->isAdminOrStaff()) {
            throw new \Cake\Http\Exception\ForbiddenException('Staffs only.');
        }
        $this->request->allowMethod(['post', 'put']);
        $this->autoRender = false;
        if (!$id) {
            throw new NotFoundException('Message ID is required.');
        }
        $contactMessages = $this->fetchTable('ContactMessages');
        $message = $contactMessages->get($id);
        $targetStatus = $this->request->getData('is_read');
        $message->is_read = isset($targetStatus) ? (int)$targetStatus : ($message->is_read ? 0 : 1);
        $success = (bool)$contactMessages->save($message, ['validate' => false]);
        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode([
                'success' => $success,
                'is_read' => $message->is_read,
                'id' => $id,
            ]));
    }

    public function deleteMessage($id = null)
    {
        if (!$this->isAdminOrStaff()) {
            throw new \Cake\Http\Exception\ForbiddenException('Staffs only.');
        }
        $this->request->allowMethod(['post', 'delete']);
        $this->autoRender = false;

        if (!$id) {
            throw new NotFoundException('Message ID is required.');
        }

        $contactMessages = $this->fetchTable('ContactMessages');
        $message = $contactMessages->get($id);

        $success = (bool)$contactMessages->delete($message);

        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode([
                'success' => $success,
                'id' => $id,
            ]));
    }
}
