<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele Termini
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Form;

use Application\Admin\Utilities\PanelsManager;

class PanelsManagerFieldset extends PanelFieldset
{
    protected $pm;

    public function __construct($key, $is_rel = false)
    {
        parent::__construct($key, $is_rel);

        $this->pm = new PanelsManager();
    }

    public function getPanels()
    {
        return $this->pm;
    }

    /**
     * {@inheritdoc}
     */
    public function getStartCode()
    {
        $code = '';

        if ($this->getContainer()->hasField('sidebar')) {
            $code = '<div class="panels-wrapper">';
        }

        $code .= '<div class="panels-container">' . ($this->getDescription() ? '<p>' . $this->getDescription() . '</p>' : '');

        return $code . $this->getTabsCode();
    }

    /**
     * @return string
     * @throws \LogicException
     */
    protected function getTabsCode()
    {
        foreach ($this->getFields() as $field) {
            if ($field instanceof PanelFieldset) {
                $this->pm->attachPanel($field->getPanel($field->getKey()));
            } else {
                throw new \LogicException(sprintf(
                    'The PanelsManagerFieldset %s accepts only PanelFieldset fields as children, instead a %s was configured',
                    $this->getKey(),
                    $field::class
                ));
            }
        }

        return $this->pm->renderTabs();
    }

    /**
     * {@inheritdoc}
     */
    public function getContentCode()
    {
        /** @var $field \Application\Admin\Form\PanelFieldset */
        foreach ($this->getFields() as $field) {
            if ($field instanceof PanelFieldset) {
                $this->pm->attachPanel($field->getPanel($field->getKey()));
            } else {
                throw new \LogicException(sprintf(
                    'The PanelsManagerFieldset %s accepts only PanelFieldset fields as children, instead a %s was configured',
                    $this->getKey(),
                    $field::class
                ));
            }
        }

        return $this->pm->render();
    }

    /**
     * {@inheritdoc}
     */
    public function getEndCode()
    {
        $code = '</div>';

        if ($this->getContainer()->hasField('sidebar')) {
            $code .= '</div>';
        }

        return $code;
    }
}
