<?php

namespace KupShop\KupShopBundle\Resources\upgrade;

use Query\Operator;

class GoogleOldToNewUpgrade extends \UpgradeNew
{
    public function check_sectionsFeedGoogleMigrateToNewIds()
    {
        return $this->checkDataMigration(23);
    }

    /** Migrate sections old ids feed_google to the new ids */
    public function upgrade_sectionsFeedGoogleMigrateToNewIds()
    {
        $pairedSections = sqlQueryBuilder()->select('s.id s_id, fg.id g_id, fg.id_old g_id_old')
            ->from('sections', 's')
            ->innerJoin('s', 'kupshop_shared.feed_google', 'fg', 's.feed_google = fg.id_old')
            ->execute()->fetchAllAssociative();

        foreach ($pairedSections as $section) {
            $newId = ((int) $section['g_id']) ?: null;
            sqlQueryBuilder()->update('sections')
                ->directValues(['feed_google' => $newId])
                ->where(Operator::equals(['id' => $section['s_id']]))
                ->execute();
        }

        $this->commitDataMigration(23);
        $this->upgradeOK();
    }

    public function check_GoogleIdIndex(): bool
    {
        return $this->checkIndexNameExists('kupshop_shared.feed_google', 'feed_google_id_index');
    }

    /** Add index on column `kupshop_shared.feed_google`.id */
    public function upgrade_GoogleIdIndex(): void
    {
        sqlQuery('create index feed_google_id_index on kupshop_shared.feed_google (id);');

        $this->upgradeOK();
    }
}
