<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Categories\Edit;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Helper\ReviewStatus as ReviewHelper;
use WriteTextAI\WriteTextAI\Model\Categories\ReviewStatus;

class Review extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::review';

    /**
     * @var ReviewHelper
     */
    protected $reviewHelper;

    /**
     * @var ReviewStatus
     */
    protected $reviewStatus;

    /**
     * Constructor
     *
     * @param Context $context
     * @param ReviewHelper $reviewHelper
     * @param ReviewStatus $reviewStatus
     */
    public function __construct(
        Context $context,
        ReviewHelper $reviewHelper,
        ReviewStatus $reviewStatus
    ) {
        $this->reviewHelper = $reviewHelper;
        $this->reviewStatus = $reviewStatus;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        try {
            $textType = $this->getRequest()->getParam('text_type');
            $storeId = $this->getRequest()->getParam('store_id');
            $categoryId = $this->getRequest()->getParam('category_id');

            $this->reviewStatus->updateReview([$textType], $categoryId, [$storeId]);

            $updatedReview = $this->reviewHelper->getCategoryReviewStatus($categoryId, $storeId);

            $result = [
                'success' =>  true,
                'updatedReview' =>  $updatedReview
            ];
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }

            $result = [
                'success' =>  false,
                'message' =>  $message
            ];
        }

        $response->setData($result);

        return $response;
    }
}
