<?php

declare(strict_types=1);

namespace External\HannahBundle\EventSubscriber;

use KupShop\UserBundle\Event\UserRegisteredEvent;
use Query\Operator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UserSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserRegisteredEvent::class => [
                ['setUserPriceLevel', 200],
            ],
        ];
    }

    /**
     * Nastaví cenovou hladinu nově registrovanému uživateli.
     *
     * Výchozí cenová hladina je "7", ale pokud byl zákazník založen na prodejně a má nastavenou
     * kartu, která začíná na "999", tak nastavuju lepší cenovou hladinu "8".
     */
    public function setUserPriceLevel(UserRegisteredEvent $event): void
    {
        $user = $event->getUser();

        $data = sqlGetConnection()->transactional(function () use ($user) {
            return $user->getCustomData(true)['sap'] ?? [];
        });

        $priceLevelName = '7';
        foreach ($data['cards'] ?? [] as $card) {
            $card = (string) $card;
            if (str_starts_with($card, '9997')) {
                // cenava hladina PROFI pokud karta zacina na 9997
                $priceLevelName = '35';
                break;
            } elseif (str_starts_with($card, '9996')) {
                // cenava hladina PARTNER pokud karta zacina na 9996
                $priceLevelName = '33';
                break;
            } elseif (str_starts_with($card, '999')) {
                // cenava hladina Junior pokud karta zacina na 999
                $priceLevelName = '8';
                break;
            }
        }

        if ($priceLevelId = $this->getPriceLevelIdByDescr($priceLevelName)) {
            try {
                sqlQueryBuilder()
                    ->insert('users_dealer_price_level')
                    ->directValues(
                        [
                            'id_user' => $user->id,
                            'id_price_level' => $priceLevelId,
                        ]
                    )->execute();
            } catch (\Throwable $e) {
                getRaven()->captureException($e);
            }
        }
    }

    private function getPriceLevelIdByDescr(string $descr): ?int
    {
        $priceLevelId = sqlQueryBuilder()
            ->select('id')
            ->from('price_levels')
            ->where(Operator::equals(['descr' => $descr]))
            ->execute()->fetchOne();

        return $priceLevelId ? (int) $priceLevelId : null;
    }
}
