<?php

namespace Eadesigndev\RomCity\Block\Checkout;

use Eadesigndev\RomCity\Model\RomCityRepository;
use Eadesigndev\RomCity\Model\RomCity;
use Eadesigndev\RomCity\Model\ResourceModel\Collection\Collection;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\View\Element\Template;
use Magento\Directory\Helper\Data;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\App\CacheInterface;
/**
 * Class Cities
 * @package Eadesigndev\RomCity\Block\Checkout
 */

#[\AllowDynamicProperties]
class Cities extends Template
{
    private $helperData;

    private $romCityRepository;

    private $romCityModel;

    private $collection;

    private $searchCriteria;

    private $cacheId = 'Eadesigndev_RomCity_Countries';
    private $cache;
    private $serializer;

    public function __construct(
        Template\Context $context,
        Data $helperData,
        RomCity $romCityModel,
        Collection $collection,
        RomCityRepository $romCityRepository,
        SearchCriteriaBuilder $searchCriteria,
        SerializerInterface $serializer,
        CacheInterface $cache,
        array $data = []
    ) {
        $this->romCityModel = $romCityModel;
        $this->searchCriteria = $searchCriteria;
        $this->collection = $collection;
        $this->helperData   = $helperData;
        $this->romCityRepository = $romCityRepository;
        $this->cache = $cache;
        $this->serializer = $serializer;

        parent::__construct($context, $data);
    }

    public function citiesJson()
    {
        $countriesArrayUpdated = $this->loadDataFromCache();

        if (!$countriesArrayUpdated) {
            $countriesJson = $this->helperData->getRegionJson();
            $countriesArray = json_decode($countriesJson, true);

            $searchCriteriaBuilder = $this->searchCriteria;
            $searchCriteria = $searchCriteriaBuilder->create();

            $citiesList = $this->romCityRepository->getList($searchCriteria);
            $items = $citiesList->getItems();

            /** @var RomCity $item */
            foreach ($items as $item) {
                $citiesData[$item->getEntityId()] = $item;
            }

            $countriesArrayUpdated = [];

            foreach ($countriesArray as $countryCode => $regionsInCountry) {
                if ($countryCode == 'config') {
                    $countriesArrayUpdated[$countryCode] = $regionsInCountry;
                    continue;
                }

                $regions = [];
                foreach ($regionsInCountry as $regionId => $region) {
                    foreach ($citiesData as $cityId => $cityData) {
                        $entityId = $cityData->getRegionId();
                        if ((int)$entityId === (int)$regionId) {
                            $id = $cityData->getId();
                            $cityName = $cityData->getCityName();
                            $region['cities'][$id] = [
                                'name' => $cityName,
                                'id' => $cityId
                            ];
                        }
                    }

                    if (isset($region['cities'])) {
                        $seenCities = [];
                        foreach ($region['cities'] as $cityId => $cityData) {
                            $cityName = $cityData['name'];
                            if (in_array($cityName, $seenCities)) {
                                unset($region['cities'][$cityId]);
                            } else {
                                $seenCities[] = $cityName;
                            }
                        }
                    }

                    $regions[$regionId] = $region;
                }
                $countriesArrayUpdated[$countryCode] = $regions;
            }

            $this->saveDataInsideCache($countriesArrayUpdated);
        }

        return json_encode($countriesArrayUpdated);
    }

    public function loadDataFromCache(){
        $data = $this->cache->load($this->cacheId);
        if ($data) {
            $countriesArrayUpdated = $this->serializer->unserialize($data);
            return $countriesArrayUpdated;
        }

        return null;
    }

    public function saveDataInsideCache($countriesArrayUpdated){

        $data = $this->serializer->serialize($countriesArrayUpdated);
        $this->cache->save($data, $this->cacheId);
    }


}
