<?php

declare(strict_types=1);

namespace KupShop\ConvertorsBundle\Admin;

use Query\Operator;

class Convertors extends \Window
{
    protected $tableName = 'convertors_definition';

    public function get_vars()
    {
        $vars = parent::get_vars();

        if ($this->action == 'edit') {
            $qb = sqlQueryBuilder()->select('id, id_convertor, id_parameter, name')
                ->from('convertors_definition_parameters')
                ->where(\Query\Operator::equals(['id_convertor' => $this->getID()]))
                ->execute();

            $params = sqlFetchAll($qb, 'id');
            $params[0] = [];
            $vars['body']['data']['parameters'] = $params;
        }

        return $vars;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();
        $ID = $this->getID();

        if ($SQL) {
            $data = $this->getData();
            $parameters = getVal('parameters', $data, []);

            $this->createSQLFields('convertors_definition_parameters');
            foreach ($parameters as $id => $value) {
                $value['id_convertor'] = $ID;

                if (!empty($value['delete']) || !$id) {
                    unset($value['delete']);

                    if ($id > 0) {
                        $this->handleDeleteValue($id, $value);
                    }
                    continue;
                }

                if (empty($value['id_parameter'])) {
                    continue;
                }

                $value = $this->getSQLFields($value);

                if ($id < 0 || $this->isDuplicate()) {
                    $this->handleAddValue($value);
                } else {
                    $this->handleUpdateValue($id, $value);
                }
            }
        }

        return $SQL;
    }

    public function handleDeleteValue($id, $value)
    {
        $this->deleteSQL('convertors_definition_parameters', ['id' => $id]);
        $subQuery = sqlQueryBuilder()->select('ctv.id')
            ->from('convertors_table_values', 'ctv')
            ->innerJoin('ctv', 'convertors_table', 'ct', 'ctv.id_table = ct.id AND ct.id_convertor = :idConvertor')
            ->innerJoin('ctv', 'parameters_list', 'pl', 'ctv.id_parameter_value = pl.id AND pl.id_parameter = :idParameter')
            ->setParameter('idConvertor', $this->getID())
            ->setParameter('idParameter', $value['id_parameter']);

        sqlQueryBuilder()->delete('convertors_table_values')
            ->where(Operator::inSubQuery('id', $subQuery))
            ->execute();

        writeDownActivity(translate('logDeleteValue', 'parameters').': '.$id);
    }

    public function handleAddValue($values)
    {
        $this->insertSQL('convertors_definition_parameters', $values, ['id']);
    }

    public function handleUpdateValue($id, $values)
    {
        $this->updateSQL('convertors_definition_parameters', $values, ['id' => $id], ['id']);
    }
}

return Convertors::class;
