<?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\GridboxHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\AdminController;

class ProductoptionsController extends AdminController
{
    /**
     * @return Balbooa\Component\Gridbox\Administrator\Model
    */
    public function getModel($name = 'Productoptions', $prefix = 'Administrator', $config = ['ignore_request' => true])
    {
        return parent::getModel($name, $prefix, $config);
    }

    public function updateProductoptions()
    {
        GridboxHelper::checkUserEditLevel();
        $data = (object) [];
        $keys = ['id', 'title', 'field_type', 'required', 'file_options', 'options'];
        foreach ($keys as $key) {
            $filter = match ($key) {
                'id', 'required' => 'int',
                'title', 'field_type' => 'string',
                default => 'raw',
            };
            $default = match ($key) {
                'id', 'required' => 0,
                'title', 'field_type' => '',
                default => '{}',
            };
            $data->{$key} = $this->input->post->get($key, $default, $filter);
        }
        $model = $this->getModel();
        $model->updateProductoptions($data);
        $obj = new \stdClass();
        $obj->message = Text::_('JLIB_APPLICATION_SAVE_SUCCESS');
        $str = json_encode($obj);
        echo $str;
        exit;
    }

    public function getOptions()
    {
        $id = $this->input->get('id', 0, 'int');
        $model = $this->getModel();
        $obj = $model->getOptions($id);
        $str = json_encode($obj);
        echo $str;
        exit;
    }

    public function addProductOptions()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->addProductOptions();
        echo '{}';
        exit;
    }

    public function delete()
    {
        GridboxHelper::checkUserEditLevel();
        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $model = $this->getModel();
        $model->delete($pks);
        GridboxHelper::ajaxReload('COM_GRIDBOX_N_ITEMS_DELETED');
    }

    public function contextDelete()
    {
        GridboxHelper::checkUserEditLevel();
        $id = $this->input->get('context-item', 0, 'int');
        $array = [$id];
        $model = $this->getModel();
        $model->delete($array);
        GridboxHelper::ajaxReload('COM_GRIDBOX_N_ITEMS_DELETED');
    }
}