<?php

namespace Modules\Commande\Service;

use Entity\Model\CaEntet;
use Entity\Model\CaEvent;
use Entity\Model\Docatt;
use Entity\Model\Memos;
use Helpers\Outil\Date;
use Helpers\Trad\ITrad;
use Helpers\Validator\Validator;
use Skeleton\Router;

class AccRecepService
{
    /** @var ITrad */
    public $trad;

    /**
     * @var Router $router
     */
    public $router;

    /**
     * @var \PDO $pdo
     */
    public $pdo;

    public function __construct(ITrad $trad, \PDO $pdo, Router $router)
    {
        $this->trad = $trad;
        $this->router = $router;
        $this->pdo = $pdo;
    }

    /**
     * @return array<mixed>|null commande with its AccRecept and its Memo
     */
    public function getAccRecept(string $commandeId) :?array
    {
        // TODO : make in one query
        $commande = (new CaEntet($this->pdo))->find($commandeId);

        if (empty($commande) || $commande['DTE_AR'] == '00000000') {
            return null;
        }

        // Get last event SAR
        $listEvent = (new CaEvent($this->pdo))->findAll([
            'NO_CDE' => $commandeId,
            'AVNT' => $commande['AVENANT'],
            'CODE' => 'SAR',
        ]);

        $event = array_reduce($listEvent, function ($carry, $event) {
            if ($carry === null) {
                return $event;
            }
            return (int)($carry['NUM_ORD']) > (int)($event['NUM_ORD']) ?
                $carry : $event;
        });

        if (empty($event)) {
            throw new \Exception('Missing event SAR for commande #'.$commande['NO_CDE']);
        }
        
        return $commande + [
            'AccRecep' => [
                'Event' => $event,
                'Memo' => (new Memos($this->pdo))->find($event['NM_COMME']),
                'DocAtt' => (new Docatt($this->pdo))->find([
                    'NO_DA' => 'CA_ENTET',
                    'COD_ENR' => str_pad($commande['NO_CDE'], 9, '0', STR_PAD_LEFT),
                    'TYPE_PJ' => 'ARF',
                    //'DT_PARUT' => $commande['DTE_AR'],
                ]),
            ],
        ];
    }

    /**
     * @param array<mixed> $file
     * @return mixed
     */
    public function validateFile(Validator $validator, array $file)
    {
        $file_name = null;
        $attachedFile = $file['import_attached_file'] ?? null;
        if ($attachedFile != null
            && $attachedFile->getError() === UPLOAD_ERR_OK
        ) {
            $file_name = $attachedFile->getClientFilename();
            $validator->fileCheck(
                'fichier',
                $file_name,
                [],
                '',
                $attachedFile->getSize()
            );
        }
        return $file_name;
    }

    /**
     * @param array<mixed> $post
     */
    public function validateAccRecept(Validator $validator, array &$post) :void
    {
        $trad = $this->trad;
        $validator->isDate(
            $post['DTE_AR'],
            '',
            date('Ymd'),
            false,
            $trad->t('de l’accusé réception')
        );
        $validator->isCheck($post['AR_NCONF']);
        $validator->isStringSansEspace(
            $trad->t('Référence AR fournisseur'),
            $post['AR_REF'] ?? '',
            3,
            30
        );

        $validator->isStringAvecEspace(
            $trad->t('Commentaire'),
            $post['MEMO'] ?? '',
            0,
            3000
        );
    }

    /**
     * @param array<mixed> $commande
     * @return array<mixed>
     */
    public function getFormCommonField($commande)
    {
        $trad = $this->trad;
        return array_column([
            [
                'type' => 'DATE',
                'titre' => $trad->t(ucfirst('date d’accusé réception')),
                'name'=> 'DTE_AR',
                'pathValidator'=> $this->router->generateUri('Ajax.validator.date'),
                'paramsValidator'=> '{}',
                'value'=> !empty($commande['DTE_AR']) ?
                    (new Date())->dateConverte($commande['DTE_AR']) : '',
                'obligatoire'=> true,
            ],
            [
                'type' => 'SWITCH',
                'titre' => $trad->t('Non Conforme'),
                'name' => 'AR_NCONF',
                'value' => $commande['AR_NCONF'] ?? false,
            ],
            [
                'type' => 'TEXTE',
                'titre' => $trad->t('Référence AR fournisseur'),
                'name' => 'AR_REF',
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramsValidator' => "{'sizeMax' : '30'}",
                'value' => $commande['AR_REF'] ?? '',
                'obligatoire' => true,
            ],
            [
                'type' => 'TEXTAREA',
                'titre' => $trad->t('Commentaire'),
                'name' => 'MEMO',
                'value' => $commande['AccRecep']['Memo']['CONTMEMO'] ?? '',
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramsValidator' => "{'sizeMin' : '0', 'sizeMax' : '3000'}",
            ],
            [
                'type' => 'FILE',
                'name' => '_attached_file',
                'value' => $commande['AccRecep']['DocAtt']['NOM_ORI'] ?? null,
            ],
        ], null, 'name');
    }
}
