<?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 LatLngByCity 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;
    }

    public function execute()
    {
        $params = $this->getRequest()->getParams();

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

            $model = $this->storesFactory->create();

            $country = $params['country'] ?? null;
            $collection = $model->getAllLatLngByCity($params['city'], $country);

            $res = [];

            if ($collection->count()) {
                $res['totalRecords'] = $collection->count();
                foreach ($collection as $item) {
                    $res['items'][] = $item->getData();
                }
            }

            $resultJson->setData($res);

            return $resultJson;
        }

        return null;
    }
}
