<?php

declare(strict_types=1);

namespace Plugin\cin_portlets_5\Portlets\StartseitenArtikel;

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

use Cin\Portlets5\PortletTrait;
use JTL\Catalog\Product\Artikel;
use JTL\Helpers\Product;
use JTL\OPC\InputType;
use JTL\OPC\Portlet;
use JTL\OPC\PortletInstance;
use JTL\Shop;
use PDO;

final class StartseitenArtikel extends Portlet
{
  use PortletTrait;

  private $fontAwesome = 'fas fa-icons';

  public function getPropertyDesc(): array
  {
    return [
      'hint-for-article' => [
        'label' => __('note'),
        'type'  => InputType::HINT,
        'class' => 'warning',
        'text'  => __('hint-for-article'),
      ],
      'listStyle' => [
        'type'    => InputType::SELECT,
        'label'   => __('presentation'),
        'width'   => 66,
        'options' => [
          'gallery'      => __('presentationGallery'),
          'list'         => __('presentationList'),
          'simpleSlider' => __('presentationSimpleSlider'),
          'slider'       => __('presentationSlider'),
          'box-slider'   => __('presentationBoxSlider'),
        ],
        'default' => 'slider',
      ],
      'maxProducts' => [
        'type'     => InputType::NUMBER,
        'label'    => __('maxProducts'),
        'width'    => 33,
        'default'  => 16,
        'min'      => 0,
        'required' => true,
      ],
      'article_mode' => [
        'type'    => InputType::SELECT,
        'label'   => __('category_mode'),
        'default' => 'all',
        'options' => [
          'all'      => __('all_categories'),
          'selected' => __('selected_categories'),
          'extended' => __('extended_categories')
        ],
        'childrenFor' => [
          'selected' => [
            'selecting_categories' => [
              'label' => __('displaying_categories'),
              'type'  => InputType::TEXT_LIST,
              'width' => 33,
            ],
          ],
          'extended' => [
            'extending_category' => [
              'label' => __('displaying_extended_categories'),
              'type'  => InputType::TEXT,
              'width' => 66,
            ],
            'withoutAttribute' => [
              'type'    => InputType::CHECKBOX,
              'label'   => __('withoutAttributeToo'),
              'width'   => 33,
              'desc'    => __('withoutAttributeDescription'),
              'default' => false
            ],
          ]
        ]
      ],
    ];
  }

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

  public function getConfigPanelHtml(PortletInstance $instance): string
  {
    $cTpl = parent::getConfigPanelHtml($instance);

    return $cTpl.$this->extendConfigDialog($instance)."
    <script>
      $('#childrenFor-selected-article_mode .col-4').toggleClass('col-4 col-12');
      $('#childrenFor-selected-article_mode .form-group').addClass('row');
      $('#childrenFor-selected-article_mode .input-group').addClass('col-4 row_');
      $('#childrenFor-selected-article_mode .form-group label:first-child').addClass('col-12 row_');
    </script>";
  }

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

    $products = [];

    foreach ($this->loadArticleList($instance) as $product) {
      $products[] = (new Artikel())->fuelleArtikel((int) $product['kArtikel']);
    }

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

  private function appendCategoryFilter(string $mode, PortletInstance $instance)
  {
    $pdo = Shop::Container()->getDB()->getPDO();

    switch ($mode) {
      case 'selected':
        return "\nAND tk.cName IN (".implode(',', array_fill(0, \count($instance->getProperty('selecting_categories')), '?')).')';

        break;

      case 'extended':
        return "\nAND tk.kKategorie IN (SELECT * FROM (
          SELECT kKategorie
          FROM
            (SELECT * FROM tkategorie
            ORDER BY kOberKategorie, kKategorie) products_sorted,
            (SELECT @pv := (SELECT kKategorie FROM tkategorie WHERE cName LIKE ?)) initialisation
          WHERE   find_in_set(kOberKategorie, @pv)
          AND     length(@pv := concat(@pv, ',', kKategorie))
          ) AS subquery )";

        break;

      case 'all':
      default:
        return '';
    }
  }

  private function loadArticleList(PortletInstance $instance): array
  {
    $mode = $instance->getProperty('article_mode');
    $db   = Shop::Container()->getDB();

    $stmt = 'SELECT
      taa.kArtikel kArtikel,
      ta.cName Artikel,
      tk.cName Kategorie,
      tk.kKategorie kKategorie,
      tk.kOberKategorie parent,
      CAST(taa.cWert AS SIGNED INTEGER) sort
      FROM tartikelattribut taa
      LEFT JOIN tartikel ta ON ta.kArtikel = taa.kArtikel
      LEFT JOIN tkategorieartikel tka ON tka.kArtikel = taa.kArtikel
      LEFT JOIN tkategorie tk ON tk.kKategorie = tka.kKategorie
      WHERE ';

    $stmt .= ('extended' === $mode && $instance->getProperty('withoutAttribute')
      ? '1 = 1'
      : "taa.cName LIKE 'cin_homepage_article'");

    $prep = $db->getPDO()->prepare($stmt.$this->appendCategoryFilter($mode, $instance).' GROUP BY kArtikel');

    if ('selected' === $mode) {
      foreach ($instance->getProperty('selecting_categories') as $k => $v) {
        $prep->bindValue(($k + 1), $v);
      }
    }

    $prep->execute('extended' === $mode ? [$instance->getProperty('extending_category')] : null);

    return $prep->fetchAll(PDO::FETCH_ASSOC);
  }
}
