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

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 = 'NULL') :string
    {
        set_time_limit(0);

        $provigis = $this->getProvigisService();

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

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

            foreach (($listFournissId ?? []) as $fournissId) {
                $provigis->getFourDocAtt($fournissId);
            }
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            $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
            );
        } catch (\Exception $e) {
            $log->setLog($numeroTraitement, 'E', $e->getMessage(), (string) $e);
        }
        return $log->getEtat();
    }

    public function popupSupplierAddAction() : string
    {
        $post = $this->request->getParsedBody();
        $idFournisseur = $this->request->getAttribute('fournissId');
        
        $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 (\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()
        );
    }
}
