<?php

declare(strict_types=1);

namespace KupShop\SellerBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\SellerBundle\Utils\SellerUtil;
use Query\Operator;

class GenerateDisplayTimeScript extends Script
{
    protected static $name = '[Prodejci] Vygenerovat otevírací dobu pro zobrazeni';

    protected function run(array $arguments)
    {
        $sellerUtil = ServiceContainer::getService(SellerUtil::class);

        $days = [
            1 => 'Po',
            2 => 'Út',
            3 => 'St',
            4 => 'Čt',
            5 => 'Pá',
            6 => 'So',
            7 => 'Ne',
        ];

        foreach ($sellerUtil->getSellers() as $seller) {
            if (empty($seller['data']['opening_hours'])) {
                continue;
            }

            $previousHours = null;
            $startDay = null;
            $result = [];
            foreach ($seller['data']['opening_hours'] as $day => $hours) {
                if (!$startDay) {
                    $startDay = $day;
                }

                if (($previousHours !== null && $previousHours != $hours) || $day === 7) {
                    if (!($previousHours !== null && $previousHours != $hours)) {
                        $day = 8;
                    }

                    if ($startDay == ($day - 1)) {
                        $stringDay = $days[$startDay];
                    } else {
                        $stringDay = $days[$startDay].'-'.$days[$day - 1];
                    }

                    $openingHours = array_filter($previousHours);
                    if (!empty($openingHours)) {
                        $result[] = $stringDay.': '.implode('-', $previousHours);
                    }
                    $startDay = $day;
                }

                $previousHours = $hours;
            }

            if (!empty($result)) {
                $seller['data']['display_opening_hours'] = implode(PHP_EOL, $result);

                sqlQueryBuilder()
                    ->update('sellers')
                    ->directValues(
                        [
                            'data' => json_encode($seller['data']),
                        ]
                    )
                    ->where(Operator::equals(['id' => $seller['id']]))
                    ->execute();
            }
        }
    }
}

return GenerateDisplayTimeScript::class;
