<?php

namespace KupShop\ContentBundle\Admin;

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

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

    protected $template = 'window/pages_fragments.tpl';

    protected $tableName = 'pages';

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

    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']);
            $vars['body']['data']['blocks_history'] = $this->blocksHistory->getBlocksHistory($vars['body']['data']['id_block']);
        }

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

        return $vars;
    }

    public function processFormData()
    {
        $data = parent::processFormData();
        $this->serializeCustomData($data);

        return $data;
    }

    public function handleUpdate()
    {
        if ($result = parent::handleUpdate()) {
            $data = $this->getData();

            $ID = $this->getID();

            if ($ID) {
                $this->saveBlocks($data, $ID, $this->tableName);
            }
        }

        return $result;
    }

    public function handleDelete()
    {
        $data = $this->getObject();
        $this->removeBlocks($data['id_block']);

        return parent::handleDelete();
    }

    public function hasRights($name = null)
    {
        $obj = $this->getObject();
        $data = json_decode($obj['data'] ?: '{}', true);

        return match ($name) {
            self::RIGHT_DELETE => ($data['admin_cannot_delete'] ?? 'N') === 'N',
            default => parent::hasRights($name),
        };
    }
}

return PagesFragments::class;
