<?php
/**
 * Copyright © 2019 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace Wyomind\ElasticsearchCore\Controller\SearchTerm;

class Add extends \Magento\Framework\App\Action\Action
{


    /**
     * @var \Magento\Search\Model\Query
     */
    protected $queryModel;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Search\Model\Query $queryModel
    )
    {
        parent::__construct($context);
        $this->queryModel = $queryModel;
    }


    /**
     * Execute action based on request and return result
     * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\App\ResponseInterface
     * @throws \Magento\Framework\Exception\NotFoundException
     */
    public function execute()
    {
        $term = $this->getRequest()->getParam('term');
        $numResults = $this->getRequest()->getParam('num_results');
        

        try {

            $queryModel = $this->queryModel;
            $queryModel->loadByQueryText($term);

            if (!empty($queryModel->getData())) {
                $queryModel->setData('popularity', $queryModel->getData('popularity') + 1);
                $queryModel->setData('updated_at', date('Y-m-d H:i:s'));
                $queryModel->setData('num_results', $numResults);
            } else {
                $queryModel->setQueryText($term);
                $queryModel->setData('popularity', 1);
                $queryModel->setData('updated_at', date('Y-m-d H:i:s'));
                $queryModel->setData('num_results', $numResults);
                $queryModel->setData('store_id', $queryModel->getStoreId());
                $queryModel->setData('display_in_terms', '1');
                $queryModel->setData('is_active', 1);
                $queryModel->setData('is_processed', 0);
            }
            $queryModel->save();
            $result = ["error" => false];
        } catch (\Exception $e) {
            $result = ["error" => true, "msg" => $e->getMessage()];
        }


        $this->getResponse()->representJson(json_encode($result));
    }
}