<?php

class SlovenskaPosta extends Delivery
{
    public static $className = 'Slovenská pošta - Balík na adresu';

    protected $heureka_delivery_id = 'SLOVENSKA_POSTA';

    protected $track_and_trace = 'https://tandt.posta.sk/zasielky/[PACKAGE_ID]';

    public static $tableName = '`kupshop_shared`.`delivery_zip_codes`';
    public static $jsonFile = 'https://test20cztest:QKCufcWs@api.balikobot.cz/sp/zipcodes/BNA';

    public function check(Cart $cart)
    {
        if ($cart->hasData('delivery') && $cart->hasData('user')) {
            $this->zipExists($cart->invoice);
            $this->zipExists($cart->delivery);
        }

        return parent::check($cart);
    }

    public function import()
    {
        $json = file_get_contents(static::$jsonFile);
        $data = json_decode_strict($json);
        if (!$data || empty($data->zip_codes)) {
            return;
        }

        sqlGetConnection()->transactional(
            function () use ($data) {
                sqlQueryBuilder()->delete(self::$tableName)->where(\Query\Operator::equals(['country' => 'SK']))->execute();
                foreach ($data->zip_codes as $post) {
                    sqlQuery(
                        'INSERT IGNORE INTO '.self::$tableName.' SET zip = :psc, time_zone = :time_zone, country = :country',
                        ['psc' => $post->zip, 'time_zone' => 0, 'country' => $post->country]
                    );
                }
            }
        );
    }
}
