<?php
namespace Modules\Tables\Controller;

use Entity\Model\FacDematAdrelec;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\StreamWrapper;
use Helpers\Fichier\Fichier;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\Trad;
use Skeleton\Controller\Controller;

class FacDematAdrElecController extends Controller
{
    public function indexAction(FacDematAdrelec $qb) :string
    {
        $post = $this->request->getParsedBody();
        (new PaginatorGestion())->generate();
        $listRow = $qb->fetchAll([], $post);
        return $this->renderer->render('@Tables/FacDematAdrElec/index', [
            'listRow' => array_map(
                fn($row) => $row + [
                    'menu' => $this->createMenuCont($row)
                ],
                $listRow
            ),
            'pagination' => PaginatorGestion::getInfoPagination(),
        ]);
    }

    public function formCreateAction() :string
    {
        return $this->renderer->render('@Tables/FacDematAdrElec/formCreate', [
        ]);
    }

    public function createAction(FacDematAdrelec $qb) :Response
    {
        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();
        $validator->isStringSansEspace('Adresse', $post['ADR_FACELEC'], 9, 100);

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        $qb->insert($post);

        return new Response(200);
    }

    public function formUpdateAction(FacDematAdrelec $qb) :string
    {
        $id = $this->request->getAttribute('id');
        return $this->renderer->render('@Tables/FacDematAdrElec/formUpdate', [
            'post' => $qb->find($id),
        ]);
    }

    public function updateAction(FacDematAdrelec $qb) :Response
    {
        $id = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();
        $validator->isStringSansEspace('Adresse', $post['ADR_FACELEC'], 9, 100);

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        $qb->update($post, ['ID' => $id]);

        return new Response(200);
    }

    public function deleteAction(FacDematAdrelec $qb) :Response
    {
        $id = $this->request->getAttribute('id');
        $qb->delete($id);
        return new Response(200);
    }

    public function formImportAction() :string
    {
        return $this->renderer->render('@Tables/FacDematAdrElec/formImport', [
        ]);
    }

    public function importAction(FacDematAdrelec $qb) :Response
    {
        $file = $this->request->getUploadedFiles()['file'] ?? null;
        if (empty($file)) {
            return new Response(400, [], 'Missing file');
        }

        $validator = $this->createValidator();
        $validator->fileCheck('Fichier', $file->getClientFilename(), ['csv']);

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        $p = StreamWrapper::getResource($file->getStream());
        while ($data = fgetcsv($p)) {
            $qb->insert(['ADR_FACELEC' => $data[0]]);
        }

        fclose($p);

        return new Response(200);
    }

//_____________________________________________________________________________
// Sub-routine

    /**
     * @param array<mixed> $entity
     * @return array<mixed>
     */
    private function createMenuCont(array $entity)
    {
        $trad = $this->getTranslationService();
        $id = $entity['ID'];
        return [
            'listeSecondaire' => [
                [
                    'libelle' => $trad->t('Modifier'),
                    'route' => 'Tables.FacDematAdrElec.formUpdate',
                    'routeParam' => ['id' => $id],
                ],
                [
                    'libelle' => $trad->t('Supprimer'),
                    'lienJs' =>
                        'popupConfirmSimple('
                        . implode(',', [
                            json_encode($trad->t('Confirmation')),
                            json_encode(Trad::strBuild(
                                $trad->t('Êtes-vous sûr de vouloir supprimer @1@ ?'),
                                $trad->t('cette adresse électronique')
                            )),
                            json_encode($this->router->generateUri(
                                'Tables.FacDematAdrElec.delete',
                                ['id' => $id]
                            )),
                            '{}',
                            '() => {window.action.arianeReload()}'
                        ])
                        . ')',
                ],
            ],
        ];
    }
}
