<?php

namespace Admin;

use KupShop\AdminBundle\AdminBlocksTrait;
use KupShop\AdminBundle\Util\BlocksHistory;
use KupShop\ContentBundle\Util\BlocksTrait;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class Producers extends \Window
{
    use BlocksTrait;
    use AdminBlocksTrait;

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

    protected $show_on_web = 'producer';

    protected $tableName = 'producers';
    protected $template = 'window/producers.tpl';

    /** @var BlocksHistory */
    private $blocksHistory;

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

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

        $data = &$vars['body']['data'];

        if (!empty($data['photo'])) {
            $data['photo'] = @getImage($this->getID(), $data['photo'], '../producer/', 7, '', strtotime($data['date_updated']));
        }

        if (findModule('sliders')) {
            $data['sliders'] = sqlFetchAll($this->selectSQL('sliders', []), ['id' => 'name']);
        }

        if (isset($data['id_block'])) {
            $data['blocks'] = $this->getBlocks($data['id_block']);
            $data['blocks_history'] = $this->blocksHistory->getBlocksHistory($data['id_block']);
        }

        $data['photos'] = sqlQueryBuilder()->select('id_photo')->from('photos_producers_relation')
            ->where(\Query\Operator::equals(['id_producer' => $this->getID()]))
            ->orderBy('position')->execute()->fetchAll();

        $this->unserializeCustomData($data);

        return $vars;
    }

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

        if (getVal('Submit')) {
            $this->serializeCustomData($data);
        }

        return $data;
    }

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

        $SQL = parent::handleUpdate();

        $ID = $this->getID();

        if ($SQL) {
            if ($this->getAction() == 'edit') {
                // historii je treba ulozit jeste pred ulozenim bloku
                $this->blocksHistory->saveBlocksHistory(getVal('blocks', $data, []));
            }
            $this->saveBlocks($data, $ID, 'producers');
            $this->updateBlocksPhotosPositions($ID, 'producers', 'id_producer');
        }

        if (!empty($_FILES['picture']['name'])) {
            $img = new \Photos('producer');
            $img->newImage($this->getID());
            $img->uploadImage($_FILES['picture']);

            if ($img->checkFileType()) {
                $img->insertImageIntoDB();

                $name = returnSQLResult('SELECT name FROM '.getTableName('producers')." WHERE id='{$this->getID()}' ");

                writeDownActivity(sprintf(getTextString('producers', 'activityPhotoAdded'), $name));
            } else {
                $this->addError(getTextString('producers', 'errorBadPhoto'));
            }
            unset($img);
        }

        if (findModule(\Modules::INDEXED_FILTER)) {
            \KupShop\IndexedFilterBundle\Util\FilterUrlDefaultValue::upgrade_filter_url('producers');
        }

        $qb = sqlQueryBuilder()->update('producers');
        ($data['top'] == 'Y') ? $qb->set('position', 'COALESCE(position, (SELECT COALESCE(MAX(position) + 1, 0) FROM producers))') : $qb->set('position', 'null');
        $qb->andWhere(Operator::equals(['id' => $data['ID']]))->execute();

        return $SQL;
    }

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

        $data = $this->getObject();
        $this->removeBlocks($data['id_block']);

        return parent::handleDelete();
    }

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

        $name = returnSQLResult('SELECT name FROM '.getTableName('producers')." WHERE id='".$this->getID()."' ");
        writeDownActivity(sprintf(getTextString('producers', 'activityPhotoDeleted'), $name));

        $this->returnOK();
    }
}

return Producers::class;
