<?php
namespace Meramo\mrm_be\Controller;

use \Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Http\JsonResponse;

class DKZController
{
  /** @var ResponseFactoryInterface */
  private $responseFactory;

  public function __construct(){
    $this->dkzer = new \Meramo\mrm_be\DKZer();
  }

  public function getBranchAction(ServerRequestInterface $request): JsonResponse
  {
    $branch = $request->getQueryParams()['branch'] ?? null;
    if(!$branch) return new JsonResponse(['data' => json_encode(['success' => false])]);

    $branchFromDkz = $this->dkzer->getBranch($branch);

    $data = ['branch' => $branch, 'list' => $branchFromDkz];
    return new JsonResponse(['data' => json_encode(['success' => true, 'data' => $data])]);
  }

  public function getListsAction(ServerRequestInterface $request): JsonResponse
  {
    $codenrs = $request->getQueryParams()['codenrs'] ?? null;
    if(!$codenrs) return new JsonResponse(['data' => json_encode(['success' => false])]);

    $dataFromDkz = $this->dkzer->getLists($codenrs);

    return new JsonResponse(['data' => json_encode(['success' => true, 'data' => $dataFromDkz])]);
  }

  public function getSearchedAction(ServerRequestInterface $request): JsonResponse
  {
    $query = $request->getQueryParams()['query'] ?? null;
    if(!$query) return new JsonResponse(['data' => json_encode(['success' => false])]);

    $dataFromDkz = $this->dkzer->getSearched($query);

    return new JsonResponse(['data' => json_encode(['success' => true, 'data' => $dataFromDkz])]);
  }

  private function log($msg, $isString = true){
    if(!$isString){
      $msg = json_encode($msg, JSON_PRETTY_PRINT);
    }
    file_put_contents('/var/www/html/typo3temp/debug.log', "--- DKZer ---".PHP_EOL.$msg.PHP_EOL, FILE_APPEND);
  }
}
