<?php

namespace KupShop\AdminBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;

class CleanText extends Script
{
    use \DatabaseCommunication;

    protected static $name = 'Odebrat inline styly/html tagy';

    protected static $defaultParameters = [
        'tables' => [
            'products' => [
                'short_descr',
            ],
        ],
        'setup' => [
            'CSS.AllowedProperties' => false,
            'CSS.ForbiddenProperties' => false,
            'HTML.AllowedElements' => false,
            'HTML.ForbiddenElements' => false,
        ],
        'example setup' => [
            'CSS.AllowedProperties' => ['height', 'text-align'],
            'CSS.ForbiddenProperties' => ['height', 'text-align'],
            'HTML.AllowedElements' => ['p', 'br'],
            'HTML.ForbiddenElements' => ['p', 'br'],
        ],
    ];

    protected function run(array $arguments)
    {
        ini_set('memory_limit', '2048M');
        ini_set('max_execution_time', 60 * 60 * 4);

        if (is_null($arguments['tables'])) {
            $this->log('Chybí argument s tabulkami nebo sloupečky!');

            return;
        }

        $this->log('Čistím inline styly...');

        $config = \HTMLPurifier_Config::createDefault();
        if (array_key_exists('setup', $arguments)) {
            foreach ($arguments['setup'] as $key => $value) {
                if (is_array($arguments['setup'][$key]) || $arguments['setup'][$key] === true) {
                    $config->set($key, $value);
                }
            }
        }
        $purifier = new \HTMLPurifier($config);

        sqlGetConnection()->transactional(function () use ($purifier, $arguments) {
            foreach ($arguments['tables'] as $tableName => $table) {
                $dbq = sqlQueryBuilder()
                    ->select('id', implode(', ', $table))
                    ->from($tableName);

                foreach ($dbq->execute() as $record) {
                    foreach ($table as $col) {
                        $record[$col] = $purifier->purify($record[$col]);
                    }
                    $this->updateSQL($tableName, $record, ['id' => $record['id']]);
                }
            }
        });

        $this->log('Vyčištěno');
    }
}

return CleanText::class;
