<?php


namespace Modules\Delegation\Controller;

use DateTime;
use Entity\Model\SigDeleg;
use GuzzleHttp\Psr7\Response;
use Helpers\Trad\ITrad;
use Modules\Delegation\Repository\Delegation;
use Modules\Delegation\Validator\AbsenceDelegationValidator;
use Skeleton\Controller\Controller;

class AbsenceDelegationController extends Controller
{
    private ITrad $trad;
    private Delegation $repository;

    public function init(): void
    {
        $this->trad = $this->getTranslationService();
        $this->repository = new Delegation($this->pdo);
    }

    public function indexAction(): string
    {
        $post = $this->request->getParsedBody();

        return $this->renderer->render('@Delegation/AbsenceDelegation/index', [
            'absenceDelegations' => $this->repository->getAbsenceDelegations($post),
            'permanentDelegations' => $this->repository->getPermanentDelegations(),
            'post' => $post
        ]);
    }

    public function createAction(): string
    {
        $debut = date('Ymd');
        $earlierDebutDate = $this->repository->getEarlierDelegationDebutDate();
        if ($earlierDebutDate['MAX'] != '') {
            $d = DateTime::createFromFormat('Ymd', $earlierDebutDate['MAX']);
            if ($d) {
                $debut = date('Ymd', strtotime('+1 day', $d->getTimestamp()));
            }
        }

        return $this->renderer->render('@Delegation/AbsenceDelegation/edit', [
            'absenceDelegations' => $this->repository->getAbsenceDelegations(),
            'permanentDelegations' => $this->repository->getPermanentDelegations(),
            'delegation' => [],
            'h2' => $this->trad->t('Création d\'une nouvelle délégation'),
            'post' => ['DTE_DEB' => $debut],
            'route' => 'Delegation.AbsenceDelegation.create',
            'label_route' => $this->trad->t('Création'),
            'path_validation' => $this->router->generateUri('Delegation.AbsenceDelegation.validate'),
            'deleg_lock' => false
        ]);
    }

    public function editAction(): string
    {
        $deleg = $this->request->getAttribute('deleg');
        $debut = $this->request->getAttribute('debut');
        $delegation = (new SigDeleg($this->pdo))->find([
            'SIGNAT' => $_SESSION['Session_Login'],
            'DELEG' => $deleg,
            'DTE_DEB' => $debut,
        ]) ?? [];

        return $this->renderer->render('@Delegation/AbsenceDelegation/edit', [
            'absenceDelegations' => $this->repository->getAbsenceDelegations(),
            'permanentDelegations' => $this->repository->getPermanentDelegations(),
            'h2' => $this->trad->t('Modification délégation'),
            'post' => $delegation,
            'route' => 'Delegation.AbsenceDelegation.edit',
            'label_route' => $this->trad->t('Modification'),
            'path_validation' => $this->router->generateUri(
                'Delegation.AbsenceDelegation.validate',
                ['deleg' => $delegation['DELEG'] ?? '', 'debut' => $delegation['DTE_DEB'] ?? '']
            ),
            'deleg_lock' => true
        ]);
    }

    /**
     * validateAction
     *
     * @return string|Response
     */
    public function validateAction()
    {
        $post = $this->request->getParsedBody();
        $deleg = $this->request->getAttribute('deleg');
        $debut = $this->request->getAttribute('debut');

        $validator = new AbsenceDelegationValidator($this->pdo, $this->trad);

        $validator->validateAbsenceDelegation($post, $deleg ?? '', $debut ?? '');

        if (!$validator->isValid()) {
            if (!$post['submitForce']) {
                $params = [
                    'alerte' => $validator->getError(),
                    'avertissement' => $validator->getErrorNonBloquant(),
                    'action' => 'creation',
                ];
                return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                    'params' => $params,
                ]);
            }
            if ($validator->getError() != '') {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }

            if (!isset($post['confirm'])) {
                return $this->createJsonResponse(
                    [
                        'type' => 'confirm',
                        'popupHtml' => $this->renderer->render('@popup-erreur/simpleWarning', [
                            'content' => $validator->getErrorNonBloquant(),
                        ]),
                    ],
                    400
                );
            }
        }

        if ($debut != '' && $deleg != '') {
            $result = (new SigDeleg($this->pdo))
                ->update([
                    'SIGNAT' => $_SESSION['Session_Login'],
                    'DELEG' => $post['DELEG'],
                    'DTE_DEB' => $post['DTE_DEB'],
                    'DTE_FIN' => $post['DTE_FIN'] == ''
                        ? '00000000'
                        : $post['DTE_FIN'],
                ], [
                    'SIGNAT' => $_SESSION['Session_Login'],
                    'DELEG' => $deleg,
                    'DTE_DEB' => $debut,
                ]);
        } else {
            $result = (new SigDeleg($this->pdo))
                ->insert([
                    'SIGNAT' => $_SESSION['Session_Login'],
                    'DELEG' => $post['DELEG'],
                    'DTE_DEB' => $post['DTE_DEB'],
                    'DTE_FIN' => $post['DTE_FIN'] == ''
                        ? '00000000'
                        : $post['DTE_FIN'],
                ]);
        }


        if ($result) {
            $path = $this->router->generateUri(
                'Delegation.AbsenceDelegation.index',
                []
            );

            return $this->createJsonResponse([
                'statut' => 'O',
                'path' => $path,
            ], 443);
        }

        return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
            'params' => [
                'alerte' => $result,
            ],
        ]);
    }

    public function deleteAction(): Response
    {
        $deleg = $this->request->getAttribute('deleg');
        $debut = $this->request->getAttribute('debut');

        $result = (new SigDeleg($this->pdo))
            ->delete([
                'SIGNAT' => $_SESSION['Session_Login'],
                'DELEG' => $deleg,
                'DTE_DEB' => $debut,
            ]);

        return $this->redirect('Delegation.AbsenceDelegation.index');
    }
}
