<?php

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

namespace Application\Admin\Controller;

use Application\Admin\Form\Generator\AdminGenerator;
use Application\Admin\Kernel;
use Application\Admin\Utilities\Panel;
use Application\Admin\Utilities\PanelsManager;
use Pongho\Form\Form;
use Pongho\Form\Utilities\FormBuilder;
use Pongho\Http\RedirectResponse;
use Pongho\Http\Response;

/**
 * Class CrudPanelsController
 *
 * @deprecated Una volta usata solo da Core\UsersController, resta come riferimento nel caso si voglia ripristinare il vecchio funzionamento, ma necessita di essere rivista
 */
abstract class CrudPanelsController extends Crud2Controller
{
    /**
     * @return \Application\Admin\Form\FormConfig
     */
    abstract protected function getFormsOptions();

    /**
     * @param Form $form
     * @return string
     */
    protected function renderForm(Form $form)
    {
        return $form->render();
    }

    /**
     * @param array $forms
     * @return null
     */
    protected function renderAddEdit(array $forms)
    {
        $this->getHelper()->getHead()
            ->addJavaScript(pongho_url('/Application/Admin/Resources/vendor/jqueryui-nestedsortable/jquery.ui.nestedSortable.js?v=' . filemtime(PONGHO_PATH . '/vendor/jQueryUI-widgets/nestedSortable/jquery.ui.nestedSortable.js')))
            ->addJavaScript(pongho_url('/Application/Admin/Resources/views/js/plugins.js?v=' . Kernel::VERSION))
            ->addJavaScript(pongho_url('/Application/Admin/Resources/views/js/scripts.js?v=' . Kernel::VERSION));

        $this->getHelper()->getBodyView()
            ->setTemplatePath(__DIR__ . '/../Resources/views/edit_panels.php')
            ->assignVars([
                'title' => $this->getAddEditTitle($this->getModel()),
                'tabs'  => $this->getPanels($forms),
            ]);

        return null;
    }


    /**
     * {@inheritdoc}
     */
    protected function addEdit()
    {
        $path = $this->getParameter('path');
        $forms = $this->getPanelsForms();

        $this->getHelper()->notify(
            $this,
            'admin.' . $this->getNamespace() . '.notify_before_render_view',
            ['model' => $this->getModel()]
        );

        if ($this->getRequest()->getMethod() === 'POST' && isset($_GET['p']) && ($tab = $_GET['p'])) {
            if (array_key_exists($tab, $forms)) {
                /** @var $form \Pongho\Form\Form */
                $form = $forms[$tab];

                $this->invokeCallBack('before_save', $form, []);

                // risolvo la form
                $form->handleRequest($this->getRequest());

                if (!$form->hasErrors()) {
                    $this->invokeCallBack('after_save', $form, []);
                }

                if ($this->action === 'add') {
                    if (!$form->hasErrors()) {
                        return new RedirectResponse($this->url('/' . $path . '/edit/' . $form->getSubject()->get('id') . '/'));
                    }
                } else {
                    return new Response($this->renderForm($form));
                }
            }
        }

        return $this->renderAddEdit($forms);
    }

    /**
     * @return array
     */
    protected function getPanelsForms()
    {
        static $forms;

        if ($forms === null) {
            $path = $this->getParameter('path');

            $action = $this->action === 'add' ? ('/' . $path . '/add/') : ('/' . $path . '/edit/' . $this->getModel()->id . '/');

            $forms = [];

            foreach ($this->getFormsOptions() as $name => $options) {
                /** @var \Pongho\Form\Form $form */
                $form = FormBuilder::buildConfig($options);

                $forms[$name] = $form
                    ->setAction($this->url($action . '?p=' . $name))
                    ->setGenerator(new AdminGenerator($this->getHelper()->getLocalization()));
            }
        }

        return $forms;
    }

    /**
     * @param array $forms
     * @return PanelsManager
     */
    protected function getPanels(array $forms)
    {
        static $panels;

        if ($panels === null) {
            $panels = new PanelsManager();

            /** @var \Pongho\Form\Form $form */
            foreach ($forms as $name => $form) {
                $panel = new Panel(
                    $name,
                    $this->getHelper()->getLocalization()->get($name),
                    [
                        'content' => '<div class="form-wrapper">' . $form->render() . '</div>',
                    ]
                );

                if ($this->getActivePanel($name)) {
                    $panel->setActive();
                }

                $panels->attachPanel($panel);
            }
        }

        return $panels;
    }

    /**
     * @param $name
     * @return bool
     */
    protected function getActivePanel($name)
    {
        $p = $this->getRequest()->query->get('p', false);

        if ($p === $name) {
            return true;
        }

        return $p === false && $name === 'main';
    }
}
