<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  Joomla_Administrator_Component
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace Mefi\Component\MefisAssetBridge\Administrator\Controller;

use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Route;
use Mefi\Component\MefisAssetBridge\Administrator\Traits\CoreBridgeTrait;

defined('_JEXEC') or die;


/**
 * Login Controller.
 *
 * @since  1.5
 */
class DisplayController extends BaseController
{
    use CoreBridgeTrait;
    /**
     * The default view.
     *
     * @var    string
     * @since  4.0.0
     */
    protected $default_view = 'auth';

    /**
     * Method to display a view.
     *
     * @param   boolean  $cachable   If true, the view output will be cached
     * @param   array    $urlparams  An array of safe URL parameters and their variable types.
     *                   @see        \Joomla\CMS\Filter\InputFilter::clean() for valid values.
     *
     * @return  static   This object to support chaining.
     *
     * @since   1.5
     * @throws  \Exception
     */
    public function display($cachable = false, $urlparams = false)
    {

        $view   = $this->input->get('view', $this->default_view);

        if($view == 'problems') {
            if($this->isAppRegistered()){
                // redirect
                $this->setRedirect(Route::_('index.php?option=com_mefisassetbridge&view=auth', false)); return;
            }
            $this->input->set('view', $view);
            return parent::display();
        } else {
            // check do we have problems
            if(!$this->isAppRegistered()){
                $this->setRedirect(Route::_('index.php?option=com_mefisassetbridge&view=problems', false), Text::_('COM_MEFISASSETBRIDGE_APP_NOT_REGISTERED'), 'error');
                return;
            }
        }
        // Authentication logic
        if (! $this->isAuthenticated()) {
            if($view != 'auth')
            {
                // Redirect to the auth view if not authenticated
                $this->setRedirect(Route::_('index.php?option=com_mefisassetbridge&view=auth', Text::_('COM_MEFISASSETBRIDGE_AUTH_REQUIRED')));
                return;
            }

        } else {
            if($view == 'preview') {
                $this->input->set('view', $view);
                return parent::display();
            }
            $view = 'dashboard';
            $this->input->set('view', $view);
        }

        return parent::display();
    }
}
