<?php
/**
* @package   Gridbox
* @author    Balbooa http://www.balbooa.com/
* @copyright Copyright @ Balbooa
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

namespace Balbooa\Component\Gridbox\Administrator\Controller;

defined('_JEXEC') or die;

use Balbooa\Component\Gridbox\Administrator\Helper\SidebarHelper;
use Balbooa\Component\Gridbox\Administrator\Model\DashboardModel;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Controller\FormController;

class DashboardController extends FormController
{
    public function getModel($name = 'Dashboard', $prefix = 'Administrator', $config = ['ignore_request' => false])
	{
		return parent::getModel($name, $prefix, $config);
	}
    
    public function renderWidget()
    {
        $user = Factory::getUser();
        if (!$user->authorise('core.tools', 'com_gridbox')){
            exit;
        }
        $data = $this->input->get('widget', '{}', 'raw');
        $widget = json_decode($data);
        $ind = $this->input->get('ind', 0, 'int');
        /** @var DashboardModel $model */
        $model = $this->getModel();
        $html = $model->renderWidget($widget, $ind);
        echo $html;
        exit;
    }

    public function saveDashboard()
    {
        $user = Factory::getUser();
        if (!$user->authorise('core.tools', 'com_gridbox')){
            exit;
        }
        $data = $this->input->get('data', '{}', 'raw');
        $dashboard = json_decode($data);
        /** @var DashboardModel $model */
        $model = $this->getModel();
        $model->saveDashboard($dashboard);
        exit;
    }

    public function saveSidebar(): void
    {
        $user = Factory::getUser();
        if (!$user->authorise('core.tools', 'com_gridbox')){
            exit;
        }
        $data = $this->input->get('data', '{}', 'raw');
        SidebarHelper::saveSidebar($data);
        $html = SidebarHelper::make()::getCustomTree();
        echo $html;
        exit;
    }
}