<?php

namespace KupShop\ProductsChargesBundle\Admin;

use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\ProductsChargesBundle\Translations\ProductsChargesTranslation;

class ProductsCharges extends \Window
{
    protected $tableName = 'charges';
    protected $nameField = 'admin_title';

    protected $required = [
        'admin_title' => true,
    ];

    protected $defaults = [
        'figure' => 'Y',
    ];

    public function get_vars()
    {
        $vars = parent::get_vars();
        $pageVars = getVal('body', $vars);

        $vatValue = 0;
        if (!empty($pageVars['data']['vat'])) {
            $vatValue = getVat($pageVars['data']['vat']);
        }

        $pageVars['data']['vatValue'] = $vatValue;
        $pageVars['data']['price'] = toDecimal($pageVars['data']['price'] ?? 0);
        $pageVars['data']['currencies'] = Contexts::get(CurrencyContext::class)->getSupported();
        $pageVars['data']['translation_figure'] = $this->getTranslationUtil()?->getTranslationsFigure(ProductsChargesTranslation::class, $this->getID());
        $this->unserializeCustomData($pageVars['data']);

        $pageVars['vats'] = \KupShop\KupShopBundle\Context\VatContext::getAdminVats(true);

        $vars['body'] = $pageVars;

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        if (getVal('Submit')) {
            $this->serializeCustomData($data);
            if ($data['priceWithVat'] && $data['price'] > 0) {
                $data['price'] = toDecimal($data['price'])->removeVat(getVat($data['vat']));
            }
            if (trim($data['product']) === '') {
                $data['id_product'] = '';
                $data['id_variation'] = '';
            }
        }

        return $data;
    }

    public function handleUpdate()
    {
        $data = $this->getData();

        $result = parent::handleUpdate();

        if ($result) {
            // Save translations figure
            $this->getTranslationUtil()?->updateTranslationsFigure(ProductsChargesTranslation::class, $this->getID(), $data['translation_figure'] ?? []);
        }

        return $result;
    }
}

return ProductsCharges::class;
