<?php

namespace FiloBlu\Storelocator\Controller\Index;

use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;

/**
 *
 */
class CitiesByRegion extends Action
{
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    private $resultJsonFactory;
    /**
     * @var \FiloBlu\Storelocator\Model\StoresFactory
     */
    private $storesFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \FiloBlu\Storelocator\Model\StoresFactory $storesFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        StoresFactory $storesFactory
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->storesFactory = $storesFactory;
    }

    /**
     * Execute action based on request and return result
     *
     * @return \Magento\Framework\Controller\ResultInterface
     * @throws \Magento\Framework\Exception\NotFoundException
     */
    public function execute()
    {
        $params = $this->getRequest()->getParams();

        if ($params['ajax'] == 1 && $params['region'] && $this->getRequest()->isXmlHttpRequest()) {
            $resultJson = $this->resultJsonFactory->create();

            $model = $this->storesFactory->create();
            $collection = $model->getCitiesByRegionHTML($params['region']);

            $resultJson->setData($collection);

            return $resultJson;
        }

        return null;
    }
}
