<?php
namespace Modules\Consultation\Controller;

use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;
use Skeleton\Controller\Controller;
use Helpers\Ariane\ArianeSub;
use Modules\Consultation\Repository\GestionConsultation;
use Modules\Consultation\Repository\AoEvent;
use Helpers\Trad\Trad;
use Modules\ProjetAchat\Repository\Action;
use Modules\Consultation\Repository\Consultation;
use Entity\Model\TypePj;
use Helpers\Outil\Sql;
use Modules\Consultation\WebService\PiecesJointes;
use Modules\GlobalApplication\Repository\DocumentsRattaches;
use Helpers\Session\ParseBase1;

class ImportDocumentController extends Controller
{
    public function listeDocumentAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();
        
        $gestionConsu = new GestionConsultation($this->pdo);
        $consultation = $gestionConsu->getInfoAo($idAO);
        
        $aoEvent = new AoEvent($this->pdo);
        $AOEventCreat = $aoEvent->getNameCreate($idAO);
        
        $trad = $this->getTranslationService();
        
        ArianeSub::generate(1, 0, $trad->t('Liste documents'), $_SERVER['REQUEST_URI'], 1);
        
        $listeTypeEntity = new TypePj($this->pdo);
        $listeTypeTmp = $listeTypeEntity->fetchAll();
        
        $listeType = [];
        foreach ($listeTypeTmp as $type) {
            $listeType[$type['PJ_TYPE']] = $type['PJLIBELLE'];
        }
        
        $actionRepo = new Action($this->pdo);
        $listeProjetTMP = $actionRepo->checkLienExterneProjetExist($idAO, 'NO_AO');
        
        $listeProjet = [];
        foreach ($listeProjetTMP as $projet) {
            $listeProjet[] = $projet['ID_OBJET'];
        }
        
        $implodeProjet = implode("','", $listeProjet);
        
        $consultationRepo = new Consultation($this->pdo);
        $listeDoc= $consultationRepo->getListeDoc($implodeProjet);
        
        return $this->renderer->render('@Consultation/Consultation/ImportDocument', [
            'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc':'Consultations',
            'menuLeft'          => 'gestionAO',
            'idAO'              => $idAO,
            'post'              => $post,
            'consultation'      => $consultation,
            'AOEventCreat'      => $AOEventCreat,
            'listeDoc'          => $listeDoc,
            'listeType'         => $listeType,
            'idAOforDoc'        => str_pad($idAO, 9, '0', STR_PAD_LEFT),
            'mode'              => $mode,
        ]);
    }

    public function ajaxImportDocAction() : string
    {
        $idSource = $this->request->getAttribute('idSource');
        $noOrder = $this->request->getAttribute('noOrder');
        $idDestination = $this->request->getAttribute('idDestination');
        
        $docAtt = new DocumentsRattaches($this->pdo);
        $infoDoc = $docAtt->docAttAvecMemos($idSource, $noOrder, 'DOA');
        
        $path_info = pathinfo($infoDoc['NOM_FIC']);
        
        list(, $sec) = explode(' ', microtime());
        
        $sec .= $sec.rand(1, 999999);
        
        $new_name = $sec . '.' . ($path_info['extension'] ?? '');
        
        $oldFic = (new ParseBase1())->getRep()->pj.$infoDoc['NOM_FIC'];
        $newFic = (new ParseBase1())->getRep()->tmp.$new_name;
        
        copy($oldFic, $newFic);

        $value=[
            "NO_FAC" => $idDestination,
            "NO_ORDRE" => '',
            "new_name" => $new_name,
            "file_name" => $infoDoc['NOM_ORI'],
            "typePj" => $infoDoc['TYPE_PJ'],
            "titreDoc" =>$infoDoc['TITRE'],
            "LECTURE" => 1,
            "IMP_PJ" => Sql::boolSql($infoDoc['PJ_CDE']),
            "IMP_TITRE" => 1,
        ];
        
        $pjWebServiceConsultation = new PiecesJointes();
        $res = $pjWebServiceConsultation->createPJ($value);

        $xmlResult = new \SimpleXMLElement($res->responseData);
        $trad = $this->getTranslationService();

        if ($xmlResult->Retour=="O") {
            return $this->renderer->render('@popup-erreur/information', [
                'message' => $trad->t('Le document a bien été importé.')
            ]);
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $xmlResult->MsgErreur,
                'desactiveRow' => true,
            ]);
        }
    }
}
