<?php

declare(strict_types=1);

namespace Cin\Portlets5;

use Exception;
use JTL\Helpers\Text;
use JTL\OPC\PortletInstance;
use JTL\Shop;

require_once 'warmup.php';

trait PortletTrait
{
  private $cinurl = 'https://www.com-ins-netz.de';

  private $cinurltext = 'www.com-ins-netz.de';

  public function __t(string $key, string $adminTranslation): string
  {
    if (isset($_SERVER['REDIRECT_URL']) && '/admin/onpagecomposer' === $_SERVER['REDIRECT_URL']) {
      return $adminTranslation;
    }

    $getText = Shop::Container()->getGetText();

    $oldLang = $getText->getLanguage();
    $getText->setLanguage(Text::convertISO2ISO639(Shop::getLanguageCode()));

    return __($key);
  }

  public function getButtonHtml(): string
  {
    if ( ! isset($this->fontAwesome)) {
      throw new Exception("Set private field fontAwesome like 'fas fa-icons' in {$this->class}", 0);
    }

    return '<i class="'.$this->fontAwesome.'" style="color:#'
      .($this->isLicensed($this->class) ? 'e87d0c' : '6c757d')
      .'"></i><span>'.$this->getTitle().'</span>';
  }

  public function getFinalHtml(PortletInstance $instance, bool $inContainer = true): string
  {
    return $this->isLicensed($this->class) ? parent::getFinalHtmlFromTpl($instance, $inContainer) : '';
  }

  public function isLicensed(string $feature): bool
  {
    $L = new Licence();

    return $L->canRun() && $L->hasFeature($feature);
  }

  public function showLicenceAlert(): bool
  {
    return ! $this->isLicensed($this->class);
  }

  public function showLicenceInfo(): string
  {
    return __('po_no_valid_licence');
  }

  public function cinUrl(): string
  {
    return $this->cinurl;
  }

  public function cinUrlText(): string
  {
    return $this->cinurltext;
  }

  protected function extendConfigDialog(PortletInstance $instance): string
  {
    return \PHP_EOL.'<script>'.\PHP_EOL
    .$this->addAttributeToConfig('min')
    .$this->addAttributeToConfig('max')
    .'</script>';
  }

  /**
   * Add javascript snippets.
   */
  private function addAttributeToConfig(string $attr): string
  {
    $returnContent = '';

    foreach ($this->getPropertyDesc() as $key => $desc) {
      if (isset($desc[$attr])) {
        $returnContent .= "$('#config-{$key}').attr('{$attr}', {$desc[$attr]})".\PHP_EOL;
      }
    }

    return $returnContent;
  }
}
