<?php

namespace KupShop\ContentBundle\View;

use KupShop\I18nBundle\Translations\BlocksTranslation;
use KupShop\KupShopBundle\Views\View;
use Query\Operator;
use Query\Translation;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class BlockEditView extends View
{
    use \DatabaseCommunication;

    protected $template = 'block_edit.tpl';

    protected string $smartyFallback = 'empty_page';

    private $blockId;

    public function setBlockId($blockId)
    {
        $this->blockId = $blockId;
    }

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

        $vars['block'] = $this->getBlock($this->blockId);

        return $vars;
    }

    private function getBlock($id)
    {
        $block = sqlQueryBuilder()->select('b.*')
            ->from('blocks', 'b')
            ->where(Translation::coalesceTranslatedFields(BlocksTranslation::class))
            ->andWhere(Operator::equals(['b.id' => $id]))
            ->execute()->fetch();

        if (!$block) {
            throw new NotFoundHttpException('Block was not found');
        }

        return $block;
    }
}
