<?php

declare(strict_types=1);

namespace Plugin\cin_portlets_5\Portlets\StartseitenKategorien;

require \dirname(__DIR__, 2).'/src/warmup.php';

use Cin\Portlets5\PortletTrait;
use JTL\Catalog\Category\Kategorie;
use JTL\Helpers\Category;
use JTL\OPC\InputType;
use JTL\OPC\Portlet;
use JTL\OPC\PortletInstance;
use JTL\Shop;
use PDO;

final class StartseitenKategorien extends Portlet
{
  use PortletTrait;

  private $fontAwesome = 'fas fa-layer-group';

  public function getPropertyDesc(): array
  {
    return [
      'hint-for-category' => [
        'label' => __('note'),
        'type'  => InputType::HINT,
        'class' => 'warning',
        'text'  => __('hint-for-category'),
      ],
      'listStyle' => [
        'type'    => InputType::SELECT,
        'label'   => __('presentation'),
        'width'   => 100,
        'options' => [
          'gallery'      => __('presentationGallery'),
          'list'         => __('presentationList'),
          'simpleSlider' => __('presentationSimpleSlider'),
          'slider'       => __('presentationSlider'),
        ],
        'default' => 'gallery',
      ],
      'maxProducts' => [
        'type'     => InputType::NUMBER,
        'label'    => __('maxProducts'),
        'width'    => 50,
        'default'  => 16,
        'min'      => 0,
        'required' => true,
      ],
      'showDescription' => [
        'type'    => InputType::CHECKBOX,
        'label'   => __('showDescription'),
        'width'   => 50,
        'default' => false
      ],
    ];
  }

  public function getConfigPanelHtml(PortletInstance $instance): string
  {
    return parent::getConfigPanelHtml($instance)
      .$this->extendConfigDialog($instance);
  }

  public function getPropertyTabs(): array
  {
    return [
      __('Styles') => 'styles',
    ];
  }

  public function getCategories(PortletInstance $instance): array
  {
    if ( ! $this->isLicensed($this->class)) {
      return [];
    }

    $db   = Shop::Container()->getDB();
    $prep = $db->getPDO()->prepare("SELECT
      tka.kKategorie,
      tk.cName,
      tka.cWert,
      CAST(IF(CAST(tka.cWert AS SIGNED INTEGER) > 0, tka.cWert, NULL) AS SIGNED INTEGER) AS cast_nWert,
      CAST(IF(CAST(tka.cWert AS SIGNED INTEGER) = 0, tka.cWert, NULL) AS CHAR) AS cast_cWert
      FROM tkategorieattribut tka, tkategorie tk
      WHERE tka.cName LIKE 'cin_homepage_category'
      AND tka.kKategorie = tk.kKategorie");
    $prep->execute();
    $rslt = $prep->fetchAll(PDO::FETCH_ASSOC);

    $rslt = array_map(static function ($o) {
      $o['C']    = new Kategorie((int) $o['kKategorie']);
      $o['subs'] = Category::getSubcategoryList((int) $o['kKategorie']);

      return $o;
    }, $rslt ?: []);

    return \array_slice($rslt, 0, $instance->getProperty('maxProducts') ?: null);
  }
}
