<?php

declare(strict_types=1);

namespace External\HannahBundle\Resources\script;

use External\HannahBundle\Email\OCSellerRegistrationEmail;
use External\HannahBundle\Util\OCImportUtil;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\DomainContext;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class OCActionScript extends Script
{
    protected static $name = '[OC] Actions script';
    protected static $defaultParameters = [
        'importProductPrices' => false,
        'resendUserCardEmails' => false,
    ];

    protected function run(array $arguments)
    {
        sqlGetConnection()->getConfiguration()->setSQLLogger();

        foreach ($arguments as $method => $run) {
            if (!$run) {
                continue;
            }

            if (!method_exists($this, $method)) {
                continue;
            }

            $this->log("Running {$method}...");
            $this->$method();
            $this->log('Completed');
        }

        $this->log('Done');
    }

    private function importProductPrices(): void
    {
        ServiceContainer::getService(OCImportUtil::class)->importProductPrices();
    }

    private function resendUserCardEmails(): void
    {
        $qb = sqlQueryBuilder()
            ->select('u.id, u.email')
            ->from('users', 'u')
            ->join('u', 'sap_users', 'su', 'u.id = su.id_user')
            ->leftJoin('u', 'users_groups_relations', 'ugr', 'ugr.id_user = u.id')
            ->leftJoin('ugr', 'users_groups', 'ug', 'ugr.id_group = ug.id')
            ->andWhere(' u.date_reg BETWEEN \'2024-08-05 09:55:00\' AND \'2024-11-11 06:44:00\'')
            ->andWhere(Operator::like(['ug.name' => 'Prodejna:%']))
            ->groupBy('u.id')
            ->orderBy('u.date_reg');

        $contextManager = ServiceContainer::getService(ContextManager::class);
        $emailService = ServiceContainer::getService(OCSellerRegistrationEmail::class);

        foreach ($qb->execute() as $i => $item) {
            $email = clone $emailService;

            $user = \User::createFromId($item['id']);
            $cards = $user->getCustomData()['sap']['cards'] ?? [];

            if (empty($cards)) {
                $this->log("[{$item['id']}] Skipping: no cards");
                continue;
            }

            $this->log("[{$item['id']}] Sending email to {$item['email']}...");

            $message = $contextManager->activateContexts(
                [
                    LanguageContext::class => $user->id_language ?? null,
                    DomainContext::class => $contextManager->getDomainFromLanguage($user->id_language ?? null),
                ],
                function () use ($user, $email) {
                    $email->setUser($user);

                    return $email->getEmail();
                }
            );
            $message['to'] = $user['email'];

            $email->sendEmail($message);

            $this->log("[{$item['id']}] Sent");

            if ($i % 500 === 0) {
                $this->log('Processed 500 items. Sleeping for 10s...');
                sleep(10);
            }
        }
    }
}

return OCActionScript::class;
