<?php

$main_class = 'DeliveryTypesPayment';

use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Exception\PaymentConfigurationException;

class DeliveryTypesPayment extends Window
{
    protected $tableName = 'delivery_type_payment';

    /** @var CurrencyContext */
    private $currencyContext;

    private ?Payment $payment = null;

    public function __construct()
    {
        $this->currencyContext = ServiceContainer::getService(CurrencyContext::class);
    }

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

        $pageVars = getVal('body', $vars);

        $payments = Payment::listClasses();
        $payments[''] = 'Žádná';
        foreach ($payments as $class => $payment) {
            $payments[$class] = $payment;
        }
        $pageVars['payments'] = $payments;

        $dbcfg = Settings::getDefault();
        $pageVars['data']['priceWithVat'] = $dbcfg['prod_prefer_price_vat'] == 'Y' || $dbcfg['prod_prefer_price_vat'] == 'F';

        if (!empty($pageVars['data']['price']) && $pageVars['data']['priceWithVat']) {
            $pageVars['data']['price'] *= 1 + (getAdminVat()['value'] / 100);
        }

        $pageVars['data']['currencies'] = $this->currencyContext->getAll();

        $this->unserializeCustomData($pageVars['data']);

        $vars['body'] = $pageVars;

        return $vars;
    }

    protected function getObject()
    {
        $data = parent::getObject();
        if ($obj = $this->getPaymentObject()) {
            $data['photo_array'] = $obj->getPhoto($data['photo'], $data['date_updated']);
        } elseif (!empty($data['photo'])) {
            // When no payment type specified
            $data['photo_array'] = getImage(
                $this->getID(),
                basename($data['photo']),
                dirname($data['photo']),
                8,
                $data['name'],
                strtotime($data['date_updated']),
            );
        }

        return $data;
    }

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

        if (getVal('Submit')) {
            if ($data['priceWithVat'] && $data['price'] > 0) {
                $data['price'] = $data['price'] / (1 + (getAdminVat()['value'] / 100));
            }
            if (!empty($data['price_buy'])) {
                $data['price_buy'] = $this->prepareVatPrice($data['price_buy']);
            }
        }

        if (!empty($data['class'])) {
            try {
                $payment = Payment::getClass($data['class']);
            } catch (PaymentConfigurationException $e) {
                $this->returnError($e->getMessage());
            }
            $data['data'] = $payment->processAdminWindowData($data['data'] ?? []);
        }
        $this->serializeCustomData($data);

        return $data;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();

        // Add photo
        if (!empty($_FILES['photo']['name'])) {
            $img = new Photos('payment');
            $img->newImage($this->getID());
            $img->uploadImage($_FILES['photo']);

            if ($img->checkFileType()) {
                $img->insertImageIntoDB();
            } else {
                $this->addError(getTextString('producers', 'errorBadPhoto'));
            }

            // Clear payment thumbnail
            $img->clearThumbnails([9]);
        }

        return $SQL;
    }

    public function handleDelete()
    {
        // Delete photo
        $img = new Photos('payment');
        $img->newImage($this->getID());
        $img->deletePhoto(false);

        parent::handleDelete();
    }

    public function handleErasephoto()
    {
        // ########################################################################
        $img = new Photos('payment');
        $img->newImage($this->getID());
        $img->deletePhoto();
        // ########################################################################

        $this->returnOK();
    }

    public function getPaymentObject(): ?Payment
    {
        if (!$this->payment) {
            $data = parent::getObject();

            if (empty($data['class'])) {
                return null;
            }

            $this->payment = Payment::getClass($data['class']);
            if ($id = $this->getID()) {
                $this->payment->setID($id);
            }
        }

        return $this->payment;
    }
}
