<?php
namespace Modules\API\APIExterne\Controller;

use API\Provigis\Exception\ProvigisWsResponseException;
use API\Provigis\ProvigisService;

use Entity\Model\Contfour;
use GuzzleHttp\Psr7\Response;
use Helpers\Log\OxaEventDet;
use Helpers\Pagination\Paginator;
use Entity\Model\Fourniss;
use Helpers\Log\LogSysteme;
use Skeleton\Controller\Controller;

class ProvigisController extends Controller
{
    public function bashAction(string $numeroTraitement = '') :string
    {
        set_time_limit(0);

        $provigis = $this->getProvigisService();

        $log = new OxaEventDet($this->pdo, $numeroTraitement);

        try {
            $info = $provigis->updateProvigisFourniss();

            foreach (($info['listFournissId'] ?? []) as $fournissId) {
                $provigis->getFourDocAtt($fournissId);
            }
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }

            $request = $e->getRequest();
            $response = $e->getResponse();

            $message = '';
            if ($response != null) {
                $message .= 'Unexpected response '
                    . $response->getStatusCode();
            } else {
                $message .= 'No response';
            }
            $message = ' for request '
                    . $request->getMethod()
                    .' "'
                    . $request->getUri()->__toString() . '"';

            $log->setLog($numeroTraitement, 'E', $message, (string) $e);
            return $log->getEtat();
        } catch (\Exception $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            $log->setLog($numeroTraitement, 'E', $e->getMessage(), (string) $e);
            return $log->getEtat();
        }
        $log->setLog(
            $numeroTraitement,
            $log->getEtat(),
            $s = count($info['listFournissId'] ?? []) . ' matched Fourniss; '
            . count($info['listUnmatched'] ?? []) . ' unmatchable Supplier',
            $s
        );
        return $log->getEtat();
    }

    public function popupSupplierAddAction() : string
    {
        $post = $this->request->getParsedBody();
        $idFournisseur = $this->request->getAttribute('fournissId');

        $fourniss = (new Fourniss($this->pdo))->find($idFournisseur);
        if ($fourniss['CODE_PAYS'] == 'FR' && empty($fourniss['NO_SIRET'])) {
            $trad = $this->getTranslationService();
            return $this->renderer->render('@Ajax/Erreur/ErreurCreation', [
                'titrePopup' => $trad->t('Fournisseur non valide'),
                'ErreurValid' => $trad->t('Un numéro Siret est requis pour cette opération.'),
            ]);
        }
        if ($fourniss['CODE_PAYS'] != 'FR' && empty($fourniss['NO_TVA_IC'])) {
            $trad = $this->getTranslationService();
            return $this->renderer->render('@Ajax/Erreur/ErreurCreation', [
                'titrePopup' => $trad->t('Fournisseur non valide'),
                'ErreurValid' => $trad->t('Un numéro de TVA intracommunautaire est requis pour cette opération.'),
            ]);
        }
        
        $contFour = new Contfour($this->pdo);
        $contactFournisseur = $contFour->findAll(
            ['CODE_FOU' => $idFournisseur],
            ['CODE_FOU', 'NOM', 'TEL','TELPORT', 'EMAIL', 'FONCTION'],
            $post
        );
        
        $paginator = new Paginator();
        
        $infoPagination = $paginator->generate($contactFournisseur, 8, $post, $this->renderer);
        
        return $this->renderer->render('@API/Provigis/popupSupplierAdd', [
            'contactFournisseur' => $contactFournisseur,
            'infoPagination' => $infoPagination,
            'idFournisseur' => $idFournisseur,
        ]);
    }

    public function supplierAddAction() :Response
    {
        $post = $this->request->getParsedBody();
        $idFournisseur = $this->request->getAttribute('fournissId');
        $fourniss = (new Fourniss($this->pdo))->find($idFournisseur);
        $contfour = (new Contfour($this->pdo))->find([
            'CODE_FOU' => $idFournisseur,
            'IND_FOU' => $post['IND_FOU'],
        ]);
        if (empty($fourniss) || empty($contfour)) {
            return new Response(404);
        }
        
        try {
            $this->getProvigisService()
                ->importFourniss(
                    $fourniss,
                    $contfour
                );
        } catch (ProvigisWsResponseException $e) {
            if ($error = $e->getError400()) {
                return new Response(400, [], 'Provigis error : #'. $error->code . ' ' . $error->message);
            }
            LogSysteme::prefixErrorLog($e->__toString());
            return new Response(500);
        } catch (\Exception $e) {
            LogSysteme::prefixErrorLog($e->__toString());
            return new Response(500);
        }
        
        return new Response(200);
    }

    private function getProvigisService() :ProvigisService
    {
        return $this->contenaire->get('ProvigisService');
    }

    public function supplierRemoveAction() :Response
    {
        $idFournisseur = $this->request->getAttribute('fournissId');
        
        try {
            $this->getProvigisService()->removeFourniss($idFournisseur);
        } catch (\Exception $e) {
            LogSysteme::prefixErrorLog($e->__toString());
            return new Response(500);
        }
        

        return new Response(200);
    }

    public function documentAction(): Response
    {
        $resp = $this->getProvigisService()
            ->getDocument($this->request->getAttribute('id'));
        if ($resp->getStatusCode() != 200) {
            $trad = $this->getTranslationService();
            return new Response(404, [], $trad->t('Ce document n\'est pas disponible'));
        }
        return new Response(
            $resp->getStatusCode(),
            $resp->getHeaders(),
            $resp->getBody()
        );
    }
}
