<?php

namespace Modules\Facture\Controller;

use Entity\Model\FactEnt;
use GuzzleHttp\Psr7\Response;
use Helpers\Form\FormBuilder;
use Modules\Facture\Repository\FactureRepo;
use Skeleton\Controller\Controller;

class FactureController extends Controller
{
    
    public function formAnnulerAction() :string
    {
        $numFact = $this->request->getAttribute('numFact');

        return $this->renderer->render('@Facture/Facture/formAnnuler', [
            'form' => $this->getFormAnnuler(),
            'numFact' => $numFact,
        ]);
    }

    /**
     * @return array<\stdClass>
     */
    private function getFormAnnuler()
    {
        $trad = $this->getTranslationService();
        return (new FormBuilder())
            ->addZoom('rectificative', 'Ajax.liste.facture', [
                'label' => $trad->t('Facture rectificative'),
                'zoom_filter' => ['ENT_VALID' => 'T'],
                'validator' => ['mandatory' => true]
            ])
            // ->addZoom('annuler', 'Ajax.liste.facture', [
            //     'zoom_filter' => ['LITIGE' => 'T'],
            //     'label' => $trad->t('Facture à annuler'),
            // ])
            ->build();
    }

    public function annulerAction(FactEnt $qbFacEnt) :Response
    {
        $numFact = $this->request->getAttribute('numFact');
        $post = $this->request->getParsedBody();

        $facture = $qbFacEnt->find($numFact);

        // Fail-safe
        if (empty($facture)) {
            return new Response(404, [], 'Invalid fac #'.$numFact);
        }

        $validator = $this->createFormValidator();

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

        (new FactureRepo($this->pdo))->annulerFacture(
            $numFact,
            $post['rectificative']
        );

        return new Response(200);
    }
}
