<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use External\ZNZBundle\Util\ZNZApi;
use External\ZNZBundle\Util\ZNZConfiguration;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class FixZNZPhotosScript extends Script
{
    protected static $name = '[ZNZ] Smazat fotky, ktere nepatri na tuhle website';
    protected static $defaultParameters = [
        'dryRun' => true,
    ];

    protected function run(array $arguments)
    {
        $configuration = ServiceContainer::getService(ZNZConfiguration::class);

        $qb = sqlQueryBuilder()
            ->select('ph.id, znz_ph.id_znz')
            ->from('photos', 'ph')
            ->join('ph', 'znz_photos', 'znz_ph', 'ph.id = znz_ph.id_photo');

        $this->log('Loading cache...');
        $cache = $this->getPhotoWebsites();

        $count = 0;
        $deleteIds = [];
        $this->log('Processing...');
        foreach ($qb->execute() as $item) {
            $websites = $cache[$item['id_znz']] ?? null;

            $isForCurrentWebsite = false;
            if ($websites !== null) {
                foreach ($configuration->getSupportedWebsites() as $website => $_) {
                    if (in_array($website, $websites)) {
                        $isForCurrentWebsite = true;
                        break;
                    }
                }
            }

            if (!$isForCurrentWebsite) {
                $this->log('Photo will be deleted: '.$item['id'].' ('.$item['id_znz'].')');
                $deleteIds[] = $item['id'];
                $count++;
            }
        }

        if ($arguments['dryRun'] === false) {
            $this->log('Processing real delete of photos...');

            foreach (array_chunk($deleteIds, 500) as $batch) {
                sqlQueryBuilder()
                    ->delete('photos')
                    ->where(Operator::inIntArray($batch, 'id'))
                    ->execute();
            }
        }

        $this->log('Deleted: '.$count);

        $this->log('Fix main images...');
        $this->fixMainImages();

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

    private function getPhotoWebsites(): array
    {
        static $cache;

        if ($cache === null) {
            $cache = [];

            $qb = $this->getZNZApi()->getConnection()->getQueryBuilder()
                ->select('IdObrazek, IdWebsite')
                ->from('wpj.MX_ProduktObrazek');

            foreach ($qb->execute() as $item) {
                if (!isset($cache[$item['IdObrazek']])) {
                    $cache[$item['IdObrazek']] = [];
                }

                $cache[$item['IdObrazek']][] = $item['IdWebsite'];
            }
        }

        return $cache;
    }

    private function fixMainImages(): void
    {
        $qb = sqlQueryBuilder()
            ->select('id_product')
            ->from('photos_products_relation')
            ->groupBy('id_product')
            ->having('MAX(show_in_lead)=\'N\'');

        foreach ($qb->execute() as $item) {
            \Photos::checkLeadPhoto('photos_products_relation', 'id_product', $item['id_product']);
        }
    }

    private function getZNZApi(): ZNZApi
    {
        static $znzApi;

        if (!$znzApi) {
            $znzApi = ServiceContainer::getService(ZNZApi::class);
        }

        return $znzApi;
    }
}

return FixZNZPhotosScript::class;
