<?php

namespace KupShop\ContentBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class FixLegacyBlocksScript extends Script
{
    protected static $name = 'Content cleanup - remove empty legacy blocks';
    protected static $defaultParameters = [
        'tables' => ['blocks', 'blocks_translations'],
        'fix' => false,
    ];

    protected function run(array $arguments)
    {
        $tables = $arguments['tables'] ?? [];
        foreach ($tables as $table) {
            $this->fixBlocks($table, $arguments['fix'] ?? false);
        }
    }

    protected function fixBlocks($table, $fix)
    {
        $this->log("Table `{$table}`: ");
        $qb = sqlQueryBuilder()
            ->select('b.id, b.json_content')
            ->from($table, 'b')
            ->andWhere(Operator::like(['b.json_content' => '%"type":"legacy"%']))
            ->andWhere(Operator::orX(
                Operator::like(['b.json_content' => '%"html":""%']),
                Operator::like(['b.json_content' => '%"html":null%'])
            ))->execute();

        $this->log('Total content blocks: '.$qb->rowCount());

        $deleted = 0;
        foreach ($qb as $item) {
            $json_content = json_decode($item['json_content'], true);
            $message = $item['id'].': blocks total = '.count($json_content);
            $block_types = array_column($json_content, 'type');
            $legacy_blocks = array_count_values($block_types)['legacy'] ?? 0;
            $message .= "; legacy blocks = {$legacy_blocks}; ";
            $fixed = $this->fixJSONContent($json_content);
            if ($fixed) {
                echo $message.'<br>';
                if ($fix) {
                    $json_content = empty($json_content) ? null : json_encode(array_values($json_content));
                    sqlQueryBuilder()->update($table)
                        ->directValues(['json_content' => $json_content])
                        ->where(Operator::equals(['id' => $item['id']]))
                        ->execute();
                }
                $deleted += $fixed;
            }
        }

        $this->log('Legacy blocks: '.$deleted);

        if ($fix) {
            $c = sqlQuery('UPDATE '.$table.' SET content = REPLACE(content, \'<div class=""></div>\', \'\')');
            $this->log('Fixed content: '.$c->rowCount());
        }
    }

    protected function fixJSONContent(array &$json_content)
    {
        $count = 0;
        foreach ($json_content as $key => $block) {
            if ($block['type'] == 'legacy') {
                if (empty($block['settings']['html'])) {
                    unset($json_content[$key]);
                    $count++;
                }
            }
        }

        return $count;
    }
}

return FixLegacyBlocksScript::class;
