<?php

declare(strict_types=1);

use Cin\Portlets5\Licence;
use JTL\Catalog\Category\KategorieListe;

require_once \dirname(__DIR__, 5).'/includes/globalinclude.php';
require \dirname(__DIR__, 3).'/src/warmup.php';

$response          = new stdClass();
$response->status  = 'success';
$response->message = '';
$response->data    = null;

/** @var Licence $L */
// @var Plugin $P

if ( ! $L->canRun() || ! $L->hasFeature(basename(\dirname(__DIR__, 1)))) {
  $response->status  = 'error';
  $response->message = 'unvalid licence or feature '.basename(\dirname(__DIR__, 1));
} else {
  $params = array_merge($_GET, $_POST);
  if ('application/json' === (getallheaders()['Content-Type'] ?? '')) {
    $params = array_merge($params, json_decode(file_get_contents('php://input'), true) ?? []);
  }

  if ('loadSubCategories' === $params['action']) {
    $categoryList = new KategorieListe();
    $categories   = $categoryList->getChildCategories((int) $params['category'], 0, 0);

    array_walk($categories, static function (&$categorie): void {
      $tmp                   = new stdClass();
      $tmp->hasSubcategories = $categorie->hasSubcategories;
      $tmp->id               = $categorie->getID();
      $tmp->cName            = $categorie->getName();
      $tmp->url              = $categorie->getURL();
      $categorie             = $tmp;
    });

    $response->data = $categories;
  } else {
    $response->status  = 'error';
    $response->message = 'inadequate action '.$params['action'];
  }
}

header('Content-Type: application/json; charset=utf-8');
exit(json_encode($response, 512));
