<?php

use KupShop\KupShopBundle\Util\DateUtil;

class OsobniOdber extends Delivery
{
    public static $type = Delivery::TYPE_IN_PERSON;
    public static $className = 'Osobní odběr';
    protected $adminWindowTemplate = 'delivery/deliveryOpeningHours.tpl';
    protected $zbozi_delivery_id = 'VLASTNI_VYDEJNI_MISTA';

    public $defaultIcon = '../../common/static/deliveries/osobni-odber.svg';

    public function processAdminWindowData($data)
    {
        if (!empty($data['opening_hours'])) {
            $dataPresent = false;
            foreach ($data['opening_hours'] as &$time) {
                if (!empty($time[0]) && !empty($time[1])) {
                    $time0 = DateTime::createFromFormat('H:i', $time[0]);
                    $time1 = DateTime::createFromFormat('H:i', $time[1]);
                    if (!$time0 || !$time1 || $time0 >= $time1) {
                        $time[0] = null;
                        $time[1] = null;
                    } else {
                        $dataPresent = true;
                    }
                } else {
                    $time[0] = null;
                    $time[1] = null;
                }
            }
            if (!$dataPresent) {
                unset($data['opening_hours']);
            }
        }

        return $data;
    }

    public function isWorkday($date, ?array $countries = null)
    {
        if (empty($this->custom_data['opening_hours'])) {
            return parent::isWorkday($date);
        }

        static $holidays = null;

        if (is_null($holidays)) {
            $holidays = Yasumi\Yasumi::create('CzechRepublic', $date->format('Y'));
        }

        if ($holidays->isHoliday($date)) {
            return false;
        }

        if (!empty($this->custom_data['opening_hours'][$date->format('N')][1])) {
            return true;
        }

        return false;
    }

    public function isOpen(): bool
    {
        $is_open = false;
        if (!empty($this->custom_data['opening_hours'])) {
            $result = DateUtil::isOpen($this->custom_data['opening_hours']);
            $this->is_open = $result['is_open_today'];
            $is_open = $result['is_open'];
        }

        return $is_open;
    }

    public function createFromArray($row)
    {
        parent::createFromArray($row);

        if (!$this->time_hours && !empty($this->custom_data)) {
            $dayofweek = (new DateTime())->format('N');
            if (isset($this->custom_data['opening_hours'][$dayofweek][1])) {
                $this->time_hours = $this->custom_data['opening_hours'][$dayofweek][1];
            }
        }
    }
}
