<?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\Panel;
use Pongho\Form\Fieldset;

class PanelFieldset extends Fieldset implements StructureFieldsetInterface
{
    protected $panel;

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

        $panel = $this->getPanel($this->getKey());

        $code .= sprintf(
            '<div class="tabsPanel" id="%s">',
            $panel->getPrefix() . '_' . $panel->getTabName()
        );

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

        return $code . ($this->getDescription() ? '<p>' . $this->getDescription() . '</p>' : '');
    }

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

        /** @var $field \Application\Admin\Form\PanelFieldset */
        foreach ($this->getFields() as $field) {
            $code .= $field->render();
        }

        return $code;
    }

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

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

        return $code . '</div>';
    }

    /**
     * Restituisce il Panel da inserire nel PanelsManager
     *
     * @param $name
     * @return \Application\Admin\Utilities\Panel
     */
    public function getPanel($name)
    {
        if ($this->panel === null) {
            $prefix = $this->getContainer()->getSetting('tab_prefix', 'tab');
            $active = $this->getContainer()->getSetting('tab_active', 'main') === $name;

            $info = parse_url((string) $this->getContainer()->getSetting('tab_url', ''));
            $qs = [];

            if (isset($info['query'])) {
                parse_str(str_replace('&amp;', '&', $info['query']), $qs);
            }

            $query = array_replace_recursive(
                $qs,
                [
                    'tabs' => [
                        $prefix => $name,
                    ],
                ]
            );

            $options = [
                'content' => '', //$this->render(),
                'link'    => $info['path'] . '?' . http_build_query($query, '', '&amp;'),
            ];

            $this->panel = new Panel($name, $this->getLabel(), $options);
            $this->panel->setActive($active);
            $this->panel->setPrefix($prefix);
        }

        return $this->panel;
    }
}
