<?php

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Settings;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Session as BackendSession;
use Magento\Framework\Controller\ResultFactory;

class TemplateSelection extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::generate';

    private const SESSION_KEY = 'wtai_template_selection';

    /**
     * @var BackendSession
     */
    private $backendSession;

    /**
     * Constructor
     *
     * @param Context $context
     * @param BackendSession $backendSession
     */
    public function __construct(
        Context $context,
        BackendSession $backendSession
    ) {
        parent::__construct($context);
        $this->backendSession = $backendSession;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $scope = (string) $this->getRequest()->getParam('scope', '');
            if ($scope === '') {
                $result->setData([
                    'success' => false,
                    'message' => 'Missing scope'
                ]);
                return $result;
            }

            $stored = $this->backendSession->getData(self::SESSION_KEY);
            if (!is_array($stored)) {
                $stored = [];
            }

            if ($this->getRequest()->isPost()) {
                $selections = $this->getRequest()->getParam('selections');
                if (!is_array($selections)) {
                    $selections = [];
                }

                $hasAnySelection = false;
                foreach ($selections as $value) {
                    if ($value !== null && $value !== '') {
                        $hasAnySelection = true;
                        break;
                    }
                }

                if ($hasAnySelection) {
                    $stored[$scope] = $selections;
                } else {
                    unset($stored[$scope]);
                }

                $this->backendSession->setData(self::SESSION_KEY, $stored);

                $result->setData([
                    'success' => true,
                    'data' => [
                        'scope' => $scope,
                        'selections' => $stored[$scope] ?? []
                    ]
                ]);
                return $result;
            }

            $result->setData([
                'success' => true,
                'data' => [
                    'scope' => $scope,
                    'selections' => $stored[$scope] ?? []
                ]
            ]);
            return $result;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = (string) __('A system error has occurred. Please try again.');
            }

            $result->setData([
                'success' => false,
                'message' => $message
            ]);
            return $result;
        }
    }
}
