<?php

namespace Modules\Ajax\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Outil\ArrayHelper;
use Helpers\Outil\ZoomHelper;
use Helpers\Pagination\PaginatorGestion;
use Skeleton\Controller\Controller;

class MultipickController extends Controller
{
    public function popupMultipickAction() :string
    {
        $post = $this->request->getParsedBody();

        $zoomPath = $post['zoomPath'];
        $zoom = ZoomHelper::getListeCallback($zoomPath, $this->contenaire);
        
        $qbClass = ZoomHelper::getEntityFromPath($zoomPath);
        if ($qbClass == null) {
            throw new \Exception('An entity is required for path "'.$zoomPath.'"');
        }
        $primaryKey = (new $qbClass($this->pdo))->getPrimaryKey();
        if (empty($primaryKey)) {
            throw new \Exception('A primary key is required for path "'.$zoomPath.'"');
        }
        $labelKey = (new $qbClass($this->pdo))->getLibelle();
        if (empty($labelKey)) {
            throw new \Exception('A label key is required for path "'.$zoomPath.'"');
        }

        //______________
        
        (new PaginatorGestion())->generate(8);
        /** @var callable */
        $callable = $zoom->callable;
        // Note : zoomFilter are the permanent filter
        $listEntity = $callable(($post['zoomFilter'] ?? []) + $post);

        $trad = $this->getTranslationService();
        return $this->renderer->render('@Ajax/Multipick/popupMultipick', [
            'primaryKey' => $primaryKey,
            'listEntity' => $listEntity,
            'infoPagination' => PaginatorGestion::getInfoPagination(),
            'post' => $post,
            'listCol' => ZoomHelper::getDisplayConfig($trad, $this->pdo, $zoomPath)->listField,
        ]);
    }


    public function readEntityAction() :Response
    {
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();
        $zoomPath = $post['zoomPath'];
        $config = ZoomHelper::getDisplayConfig($trad, $this->pdo, $zoomPath);
        
        
        $qbClass = ZoomHelper::getEntityFromPath($zoomPath);
        if ($qbClass == null) {
            throw new \Exception('An entity is required for path "'.$zoomPath.'"');
        }
        $qb = new $qbClass($this->pdo);
        $primaryKey = $qb->getPrimaryKey();
        if (empty($primaryKey)) {
            throw new \Exception('A primary key is required for path "'.$zoomPath.'"');
        }

        $listEntity = [];
        if (! empty($post['selection'])) {
            $listEntity = $qb->findAll([
                $primaryKey => $post['selection'],
            ]);
        }

        
        return $this->createJsonResponse([
            'listEntity' => array_map(function ($entity) use ($config) {
                return ArrayHelper::filterByKey($entity, array_column($config->listField, 'key'));
            }, $listEntity),
            'config' => $config,
        ]);
    }
}
