<?php

namespace KupShop\SellerBundle\Admin;

use KupShop\ContentBundle\Util\BlocksTrait;
use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\SellerBundle\Utils\CountryProvider;
use KupShop\SellerBundle\Utils\RegionProvider;
use KupShop\SellerBundle\Utils\TypeProvider;

class Sellers extends \Window
{
    use BlocksTrait;
    protected $nameField = 'title';

    public function getShowOnWeb()
    {
        if (!$this->getID()) {
            return null;
        }

        return ['url' => path('shop_seller_seller_detail', ['id_seller' => $this->getID()])];
    }

    public function get_vars()
    {
        $vars = parent::get_vars();

        $ID = $this->getID();
        $sql = sqlQuery('SELECT X(position) as x, Y(position) as y FROM sellers WHERE id=:ID', ['ID' => $ID]);
        foreach ($sql as $row) {
            $vars['body']['data']['position'] = join(', ', $row);
        }

        if (isset($vars['body']['data']['id_block'])) {
            $vars['body']['data']['blocks'] = $this->getBlocks($vars['body']['data']['id_block']);
        }

        $countryProvider = ServiceContainer::getService(CountryProvider::class);
        $regionProvider = ServiceContainer::getService(RegionProvider::class);
        $typeProvider = ServiceContainer::getService(TypeProvider::class);

        $vars['body']['data']['countryProvider'] = $countryProvider;
        $vars['body']['data']['regionProvider'] = $regionProvider;
        $vars['body']['data']['types'] = $typeProvider->getTypes();

        $this->unserializeCustomData($vars['body']['data']);

        $vars['body']['data']['flags_array'] = explodeFlags($vars['body']['data']['flags']);

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        $cfg = Config::get();
        if (!empty($cfg['Seller']['Flags'])) {
            $flags = getVal('flags', $data, []);
            $flags = join(',', $flags);
            $data['flags'] = $flags;
        }

        $this->serializeCustomData($data);

        if (getVal('Submit')) {
            preg_match_all('!\d+(?:\.\d+)?!', $data['point'], $matches);
            $data['point'] = array_map('floatval', $matches[0]);
        }

        return $data;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();
        $ID = $this->getID();

        $data = $this->getData();

        if ($SQL) {
            $this->saveBlocks($data, $ID, 'sellers');
        }

        if (!empty($data['point'][0]) && !empty($data['point'][1])) {
            sqlQuery('INSERT INTO sellers
         (id, position) VALUES
         (:ID, POINT(:x, :y))
         ON DUPLICATE KEY UPDATE position=POINT(:x, :y)', ['x' => $data['point'][0], 'y' => $data['point'][1], 'ID' => $ID]);
        }

        return $SQL;
    }
}

return Sellers::class;
