<?php

namespace Modules\Reception\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Roles;
use Helpers\Trad\ITrad;
use Helpers\Validator\Validator;
use Modules\Reception\Service\CreationBRService;
use Modules\Reception\Service\IncidentService;
use Skeleton\Controller\Controller;

class IncidentController extends Controller
{
    /**
     * @var array<mixed>
     */
    protected array $droits = [];
    /**
     * @var array<mixed>
     */
    protected array $params = [];
    private IncidentService $service;
    private CreationBRService $creationService;
    private Validator $validator;
    private ITrad $trad;

    /**
     * init
     *
     * @return void
     */
    public function init(): void
    {
        $this->service            = new IncidentService($this->pdo, $this->getTranslationService());
        $this->creationService    = new CreationBRService($this->pdo, $this->getTranslationService());
        $this->validator          = $this->createValidator();
        $this->trad               = $this->getTranslationService();

        $droits = [
            // Droit de visu des prix des commandes sur BR
            'HA_BR_PX' => Roles::droitsUtilisateur($this->pdo, 'HA_BR_PX', $_SESSION["Session_Login"]),
            // Droit de solder manuellement la commande si réception partielle
            'HA_CA_SPM' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_SPM', $_SESSION["Session_Login"]),
        ];

        $params = $this->creationService->getCreationParam();

        $this->droits = $droits;
        $this->params = $params;
    }

    public function ajaxUpdateLineIncidentAction(): Response
    {
        $post       = $this->request->getParsedBody();
        $order      = $this->request->getAttribute('order');
        $type       = $this->request->getAttribute('type');
        $mode       = $this->request->getAttribute('mode');

        $explode    = explode('-', $post['field']);
        $field      = $explode[0];
        $line       = $explode[1] ?? null;

        $this->service->updateIncidentLine($line, $field, $post['value']);

        $incident = $this->service->getIncident();
        $incidentLines = $this->service->getIncidentLines($order);

        $this->creationService->setSubArianeForResponse($order);

        return new Response(200, [], (string)json_encode([
            'statut'              => 'O',
            'incidents' => $this->renderer->render('@Reception/Creation/Tabs/incidents', [
                'incident'        => $incident,
                'incidentLines'   => $incidentLines,
                'order'           => $order,
                'type'            => $type,
                'mode'            => $mode,
            ]),
            'subAriane' => $this->renderer->render('@Reception/Creation/arianeSub')
        ]));
    }

    public function saveIncidentAction(): Response
    {
        $post   = $this->request->getParsedBody();
        $id     = $this->request->getAttribute('id');
        $type   = $this->request->getAttribute('type');
        $mode   = $this->request->getAttribute('mode');

        /** On verifie les champs **/
        $this->validator->isStringAvecEspace($this->trad->t('Commentaire'), $post['COMMENTAIRE_INCIDENT'], 0, 3000);
        $this->validator->isStringAvecEspace($this->trad->t('Type'), $post['TYPE'], 1, 60);

        if ($this->validator->isValid()) {
            $this->service->saveIncident($post);
            $response = [
                'statut'    => 'O',
                'path'      => $this->router->generateUri(
                    'Reception.CreationBR.creatEdit',
                    ['order' => $id, 'type' => $type, 'mode' => $mode, 'init' => 0, 'tab' => 'incidents']
                ),
                'post'      => [
                    'INCIDENT'    => $post,
                ]
            ];
            return new Response(200, [], (string)\json_encode($response));
        } else {
            return new Response(200, [], (string) json_encode(['erreur' => $this->validator->getError(), 'statut' => 'E']));
        }
    }

    public function ajaxDeleteIncidentAction(): Response
    {
        $this->service->deleteIncident();

        return new Response();
    }
}
