<?php

namespace FiloBlu\Storelocator\Block\Adminhtml\Stores;

use FiloBlu\Storelocator\Helper\Data;
use FiloBlu\Storelocator\Model\ResourceModel\Stores\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Directory\Model\CountryFactory;
use Magento\Ui\Component\MassAction\Filter;

/**
 * Abstract items renderer
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CheckError extends Template
{

    protected $_collectionFactory;
    protected $_helper;
    protected $_filter;
    protected $_storesCollection;
    protected $_countryFactory;


    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Ui\Component\MassAction\Filter $filter
     * @param \FiloBlu\Storelocator\Model\ResourceModel\Stores\CollectionFactory $collectionFactory
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param \Magento\Directory\Model\CountryFactory $countryFactory
     * @param array $data
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory,
        Data $helper,
        CountryFactory $countryFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_filter = $filter;
        $this->_collectionFactory = $collectionFactory;
        $this->_helper = $helper;
        $this->_countryFactory = $countryFactory;
        $this->_storesCollection = $this->_filter->getCollection($this->_collectionFactory->create());
    }

    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function checkEmptyCoordinates()
    {
        if (!$this->_helper->getConfig('filoblu_storelocator_section/check_error/check_error_empty_coordinates')) {
            return 'This check is not enabled.';
        }

        $return = '';
        foreach ($this->_storesCollection as $item) {
            if (!$item->getLatitude() || !$item->getLongitude()) {
                $return .= $item->getId() . ' - ' . $item->getTitle() . '</br>';
            }
        }

        return $return;
    }

    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function checkValidCoordinates()
    {
        if (!$this->_helper->getConfig(
            'filoblu_storelocator_section/check_error/check_error_invalid_coordinates_for_country'
        )) {
            return 'This check is not enabled.';
        }

        $return = '';
        foreach ($this->_storesCollection as $item) {
            if ($item->getLatitude() && $item->getLongitude() && $item->getCountry() && $this->isValidCountry(
                    $item->getCountry()
                )) {
                $key = $this->_helper->getConfig('filoblu_storelocator_section/general/gmaps_api_key_server_side');
                $url = $this->_helper->getConfig(
                        'filoblu_storelocator_section/geocode/gmaps_geocode_api_url'
                    ) . '?latlng=' . $item->getLatitude() . ',' . $item->getLongitude() . "&sensor=false&key={$key}";

                // get the json response
                $resp_json = file_get_contents($url);

                // decode the json
                $resp = json_decode($resp_json, true);

                if ($resp['status'] == 'OK') {
                    if ($address = $resp['results'][0]['address_components']) {
                        foreach ($address as $row) {
                            if ($row['types'][0] == 'country' && $row['short_name'] != $item->getCountry()) {
                                $return .= $item->getId() . ' - ' . $item->getTitle(
                                    ) . ' - VALID COUNTRY IS ' . $row['short_name'] . ', CURRENT IS ' . $item->getCountry(
                                    ) . '</br>';
                                break;
                            }
                        }
                    } else {
                        $return .= $item->getId() . ' - ' . $item->getTitle(
                            ) . ' - ERROR GET JSON - NO RESULTS FOR ADDRESS COMPONENTS</br>';
                    }
                } else {
                    if ($resp['status'] == 'ZERO_RESULTS') {
                        $return .= $item->getId() . ' - ' . $item->getTitle() . ' - ZERO RESULTS</br>';
                    } else {
                        if (isset($resp['error_message'])) {
                            $return .= $item->getId() . ' - ' . $item->getTitle(
                                ) . ' - ERROR GET JSON - ' . $resp['error_message'] . '</br>';
                        } else {
                            $this->_logger->debug(print_r($resp, true));
                            $return .= $item->getId() . ' - ' . $item->getTitle() . ' - UNEXPECTED ERROR</br>';
                        }
                    }
                }
            }
        }

        return $return;
    }

    /**
     * @param $countryId
     * @return bool
     */
    public function isValidCountry($countryId)
    {
        $countryInfo = $this->_countryFactory->create()->loadByCode($countryId);

        if (!$countryInfo->getName()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function checkValidCountry()
    {
        if (!$this->_helper->getConfig('filoblu_storelocator_section/check_error/check_error_invalid_country_id')) {
            return 'This check is not enabled.';
        }

        $return = '';
        foreach ($this->_storesCollection as $item) {
            if ($item->getCountry()) {
                if (!$this->isValidCountry($item->getCountry())) {
                    $return .= $item->getId() . ' - ' . $item->getTitle(
                        ) . ' - INVALID COUNTRY ID - ' . $item->getCountry() . '</br>';
                }
            } else {
                $return .= $item->getId() . ' - ' . $item->getTitle() . ' - EMPTY COUNTRY ID</br>';
            }
        }

        return $return;
    }

}
