<?php
/**
 * @package         Conditions
 * @version         23.1.9739
 * 
 * @author          Peter van Westen <info@regularlabs.com>
 * @link            http://regularlabs.com
 * @copyright       Copyright © 2023 Regular Labs All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

namespace RegularLabs\Component\Conditions\Administrator\Condition\Zoo;

defined('_JEXEC') or die;

use Joomla\CMS\Factory as JFactory;
use Joomla\CMS\Menu\MenuItem as JMenuItem;
use RegularLabs\Component\Conditions\Administrator\Condition\Condition;

abstract class Zoo extends Condition
{
    protected $request_keys = ['controller'];

    public function beforePass()
    {
        if ( ! $this->request->option == 'com_zoo')
        {
            return;
        }

        $full_request = JFactory::getApplication()->input->getArray();

        $this->request->view = $this->request->task ?: $this->request->view;

        switch ($this->request->view)
        {
            case 'item':
                $this->request->idname = 'item_id';
                break;
            case 'category':
                $this->request->idname = 'category_id';
                break;

            default:
                $this->request->idname = 'id';
                break;
        }

        if ( ! isset($full_request[$this->request->idname]))
        {
            $this->request->idname = 'id';
        }

        $this->request->id = $this->request->{$this->request->idname}
            ?? JFactory::getApplication()->input->getInt($this->request->idname, 0);

        if ($this->request->id)
        {
            return;
        }

        $app = JFactory::getApplication();

        /* @var JMenuItem $menu_item */
        $menu = empty(self::$_request->Itemid)
            ? $app->getMenu('site')->getActive()
            : $app->getMenu('site')->getItem(self::$_request->Itemid);

        if (empty($menu))
        {
            return;
        }

        $id_name = $this->request->view == 'category' ? 'category' : 'item_id';

        $this->request->id = $menu->getParams()->get($id_name, 0);
    }
}
