<?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\View\Dashboard;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Mefi\Component\MefisAssetBridge\Administrator\Traits\CoreBridgeTrait;

/**
 * Dashboard HTML View
 *
 * @since  1.0.0
 */
class HtmlView extends BaseHtmlView
{
    use CoreBridgeTrait;

    /**
     * The user email
     *
     * @var    string
     * @since  1.0.0
     */
    protected $userEmail;
    protected $userDto;
    protected $activeTokens;

    /**
     * Display the view
     *
     * @param   string  $tpl  The name of the template file to parse
     *
     * @return  void
     *
     * @since   1.0.0
     */
    public function display($tpl = null)
    {
        try {
            $rawApiKeys = $this->coreGetActiveApiKeys();
        } catch (\Exception $e) {
            if(stripos($e->getMessage(), 'Unauthorized') !== false) {

                $app = Factory::getApplication();
                $app->enqueueMessage(Text::_('COM_MEFISASSETBRIDGE_YOU_HAVE_BEEN_SIGNED_OUT'), 'warning');
                $app->redirect(Route::_('index.php?option=com_mefisassetbridge&task=auth.logout' . '&' . Session::getFormToken() . '=1', false));
                return;
            }
            // echo "Exception caught in dashboard view display: " . $e->getMessage();
            $this->setError($e->getMessage());
            $this->addToolbar();
            parent::display($tpl);
            return;
        }

        // get all active tokens
        $this->userDto      = $this->getDataFromSession();

        $this->userInfo = array(
            'email'      => $this->userDto->getUser()->getEmail(),
            'name'       => $this->userDto->getUser()->getName(),
            'level_name' => $this->userDto->getSubscription()->getLevelName(),
            'level'      => Text::_('COM_MEFISASSETBRIDGE_SUBSCRIPTION_LEVEL_' . strtoupper($this->userDto->getSubscription()->getLevelName())),
            'api_keys_string' => Text::sprintf(Text::_('COM_MEFISASSETBRIDGE_ACTIVE_MAX_API_KEYS'), $this->userDto->getUser()->getActiveTokens(), $this->userDto->getSubscription()->getTokenLimit()),
            'active_api_keys' =>  $this->userDto->getUser()->getActiveTokens(),
            'max_api_keys' => $this->userDto->getSubscription()->getTokenLimit()
        );

        if($this->userDto->getSubscription()->getMaxAssets() == 0) {
            $this->userInfo['max_assets'] = 0;
            $this->userInfo['max_assets_string'] = Text::_('COM_MEFISASSETBRIDGE_SUBSCRIPTION_UNLIMITED_ASSETS');
        } else {
            $this->userInfo['max_assets'] = $this->userDto->getSubscription()->getMaxAssets();
            $this->userInfo['max_assets_string'] = Text::sprintf(Text::_('COM_MEFISASSETBRIDGE_MAX_ASSETS'), $this->userDto->getUser()->getTotalAssets(), $this->userDto->getSubscription()->getMaxAssets());
        }

        $willRenew      = $this->userDto->getSubscription()->getWillRenew();
        $validUntilZulu = $this->userDto->getSubscription()->getValidUntilZulu();

        if ($willRenew !== null && $validUntilZulu !== null) {
            $dt  = Factory::getDate($validUntilZulu);
            $now = Factory::getDate('now');

            if ($willRenew === true) {
                $dateLabel = Text::_('COM_MEFISASSETBRIDGE_SUBSCRIPTION_RENEWAL_DATE');
            } elseif ($dt > $now) {
                $dateLabel = Text::_('COM_MEFISASSETBRIDGE_SUBSCRIPTION_VALID_UNTIL');
            } else {
                $dateLabel = Text::_('COM_MEFISASSETBRIDGE_SUBSCRIPTION_EXPIRED');
            }

            $this->userInfo['subscription_date_label'] = $dateLabel;
            $this->userInfo['subscription_date_value'] = $dt->format('j F Y', false);
        } else {
            $this->userInfo['subscription_date_label'] = null;
            $this->userInfo['subscription_date_value'] = null;
        }

        $prepared = [];
        foreach ($rawApiKeys as $token) {
            $t           = (array) $token;
            $website     = isset($t['website']) ? (array) $t['website'] : [];
            $tokenId     = $t['token_id'] ?? '';
            $siteName    = $website['name'] ?? '';
            $customName  = $siteName;
            $statusLabel = (! empty($t['status']))
                ? (Text::_('COM_MEFISASSETBRIDGE_STATUS_ACTIVE'))
                : (Text::_('COM_MEFISASSETBRIDGE_STATUS_INACTIVE'));
            $domains     = isset($website['domains']) && is_array($website['domains']) ? $website['domains'] : [];
            $domainsList = implode(', ', $domains);
            $deleteLink  = Route::_('index.php?option=com_mefisassetbridge&task=apikey.delete&id=' . urlencode($tokenId));

            $prepared[] = array_merge($t, [
                'website'      => $website,
                'custom_name'  => $customName,
                'status_label' => $statusLabel,
                'domains_list' => $domainsList,
                'delete_link'  => $deleteLink,
            ]);
        }

        $this->activeTokens = $prepared;

        $this->addToolbar();

        parent::display($tpl);
    }

    /**
     * Add the page title and toolbar
     *
     * @return  void
     *
     * @since   1.0.0
     */
    protected function addToolbar()
    {
        ToolbarHelper::title(Text::_('COM_MEFISASSETBRIDGE_DASHBOARD_TITLE'), 'dashboard');

        // Add logout button
        $toolbar = Toolbar::getInstance('toolbar');

        $toolbar->preferences('com_mefisassetbridge');
        $toolbar->divider();
        $toolbar->appendButton(
            'Link',
            'power-off',
            'COM_MEFISASSETBRIDGE_LOGOUT',
            'index.php?option=com_mefisassetbridge&task=auth.logout' . '&' . Session::getFormToken() . '=1'
        );
    }
    public function setUserDto($userDto)
    {
        $this->userDto = $userDto;
        return $this;
    }
}
