<?php

namespace KupShop\UserBundle\Resources\upgrade;

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Mail\EmailCheck;
use KupShop\KupShopBundle\Util\StringUtil;

class user_rights_version extends \UpgradeNew
{
    public function check_normalizeEmails()
    {
        return \Settings::getDefault()->user_rights_version == 4;
    }

    /** Normalize emails */
    public function upgrade_normalizeEmails()
    {
        $settings = \Settings::getDefault();

        $normalized = 0;
        $unsubscribed = 0;
        foreach (sqlQuery('SELECT id, email FROM users') as $user) {
            $email = StringUtil::normalize($user['email']);
            // remove whitespaces from email
            $email = preg_replace('/\s+/', '', $email);

            if ($email !== $user['email']) {
                try {
                    $normalized += $this->updateSQL('users', ['email' => $email], ['id' => $user['id']]);
                } catch (\Exception $e) {
                }
            }

            $emailCheck = ServiceContainer::getService(EmailCheck::class);
            if (!$emailCheck->isEmailDomainValid($email)) {
                $unsubscribed += $this->updateSQL('users', ['get_news' => 'N'], ['id' => $user['id']]);
            }
        }

        $this->commitDataMigration(5);

        print_r(['normalized' => $normalized, 'unsubscribed_emails' => $unsubscribed]);

        $this->upgradeOK();
    }
}
