<?php
    declare(strict_types=1);

    namespace Icing\Controller;

    use Cake\Http\Response;
    use Icing\Model\API\QuickbooksClient;
    use Icing\Model\Table\SettingsTable;
    use Psr\Log\LogLevel;
    use Throwable;

    /**
     * Quickbooks Controller
     * @property \Icing\Model\Table\SettingsTable $Settings
     *
     */
    class QuickbooksController extends AppController
    {

        protected ?SettingsTable $Settings;
        protected ?string $defaultTable = 'Icing.Settings';

        public function initialize(): void
        {
            parent::initialize();
            $this->Authentication->allowUnauthenticated(['connect', 'webhooks']);
        }

        /**
         * @throws \QuickBooksOnline\API\Exception\SdkException
         */
        public function index(): ?Response
        {
            $client = QuickbooksClient::create();
            try {
                $company = $client->getCompanyInfo();
                $this->set(compact('company'));
            } catch (Throwable) {
            }

            $this->set(compact('client'));
            return null;
        }

        /**
         * @throws \QuickBooksOnline\API\Exception\ServiceException
         * @throws \QuickBooksOnline\API\Exception\SdkException
         */
        public function connect(): ?Response
        {
            $this->autoRender = false;
            QuickbooksClient::create()->exchangeAuthorizationCodeForToken($_SERVER['QUERY_STRING']);
            return null;
        }

        public function disconnect(): ?Response
        {
            $this->getRequest()->allowMethod(['post']);
            try {
                QuickbooksClient::create()->revokeAccessToken();
                $this->Flash->success('You have disconnected the quickbooks online company.');
            } catch (Throwable) {
                $this->Flash->error('There was a problem disconnecting the quickbooks online company.');
            }
            return $this->redirect($this->referer());
        }

        /**
         * @throws \QuickBooksOnline\API\Exception\ServiceException
         * @throws \QuickBooksOnline\API\Exception\SdkException
         */
        public function webhooks(): ?Response
        {
            $this->autoRender = false;
            $this->log(json_encode($this->getRequest()->getParsedBody()), LogLevel::INFO, ['scope' => 'qb']);
            QuickbooksClient::create()->processWebhook($this->getRequest());
            echo 'OK';
            return null;
        }

    }
