<?php

use KupShop\KupShopBundle\Util\Functional\Mapping;

class UrgentCargus extends Delivery
{
    public static $className = 'Urgent Cargus';

    public static $tableName = '`kupshop_shared`.`delivery_ro_regions`';

    public static $xmlRegions = 'https://export.balikobot.cz/pbh_ro_cargus.xml';

    private $county;

    public static function isEnabled()
    {
        return findModule('deliveries', 'ro_deliveries');
    }

    public function getCounty()
    {
        if ($this->county) {
            return $this->county;
        }

        $county = sqlQueryBuilder()->select('county')
            ->from(self::$tableName)
            ->groupBy('county')
            ->orderBy('county', 'ASC')
            ->execute()->fetchAll();

        return $this->county = Mapping::mapKeys($county, function ($k, $v) {
            return [$k, $v['county']];
        });
    }

    public function getCities($county)
    {
        $cities = sqlQueryBuilder()->select('city')
            ->from(self::$tableName)
            ->where(\Query\Operator::equals(['county' => $county]))
            ->orderBy('city', 'ASC')
            ->execute()->fetchAll();

        return Mapping::mapKeys($cities, function ($k, $v) {
            return [$k, $v['city']];
        });
    }

    public function import()
    {
        $xml = simplexml_load_file(static::$xmlRegions);
        if (!$xml) {
            return;
        }

        sqlQuery('TRUNCATE TABLE '.self::$tableName);
        foreach ($xml->lokalita as $location) {
            sqlQueryBuilder()->insert(self::$tableName)->directValues([
                'county' => $location->county->__toString(),
                'city' => $location->mesto->__toString(),
            ])->execute();
        }
    }
}
