<?php

namespace KupShop\ReturnsBundle\Admin;

use KupShop\ContentBundle\Util\BlocksTrait;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class returnDelivery extends \Window
{
    use BlocksTrait;
    protected $nameField = 'name';
    protected $tableName = 'return_delivery';

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

        if (isset($vars['body']['data']['id_block'])) {
            $vars['body']['data']['blocks'] = $this->getBlocks($vars['body']['data']['id_block']);
        }

        $returnDelivery = ServiceContainer::getService(\KupShop\ReturnsBundle\Deliveries\Utils\ReturnDeliveries::class);
        $vars['body']['types'] = $returnDelivery->getAllDeliveryTypes();
        $vars['body']['data']['custom_data'] = $this->getCustomData();

        $vars['body']['currencies'] = ServiceContainer::getService(CurrencyContext::class)->getSupported();
        $icon = '../return_delivery/'.$vars['body']['data']['photo'];
        $vars['body']['data']['photo_array'] = getImage($this->getID(), basename($icon), dirname($icon), 109);

        return $vars;
    }

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

        $data['price'] = $this->prepareVatPrice($data['price']);

        $this->serializeCustomData($data);
        $data['data'] = $data['data'] ?: '';

        return $data;
    }

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

        // Add photo
        $img = new \Photos('return_delivery');
        $img->newImage($this->getID());

        if (!empty($_FILES['photo']['name'])) {
            $img->uploadImage($_FILES['photo']);

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

        $img->clearThumbnails([109]);

        return $ret;
    }

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

        parent::handleDelete();
    }

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

        $this->returnOK();
    }
}

return returnDelivery::class;
