<?php

namespace Modules\Stock\Service;

use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Parametres\Constante;
use PDO;
use Exception;

readonly class CsInitializerService
{
    public function __construct(private PDO $pdo)
    {
    }

    /**
     * @param array<string,mixed> $post
     * @param string $tableDestinataire
     * @param array<int,array<int,array<string>|string>> $tablesSources
     * @param string $codeEnr
     * @param string|null $codeSte
     * @return void
     * @throws Exception
     */
    public function initializeCs(array &$post, string $tableDestinataire, string $codeEnr, array $tablesSources, ?string $codeSte = null): void
    {
        /**
         * @var string $tableSource
         */
        foreach ($tablesSources as [$tableSource, $id]) {
            $sourceCodeEnr = $this->getSourceCodeEnr($tableSource, $id, $codeSte);
            $csSourceInit = ChampSupp::initCs($tableDestinataire, $tableSource, $sourceCodeEnr, $this->pdo);

            foreach ($csSourceInit as $cs) {
                $inputName = 'CS_EXTENTION'.Constante::spliter.$tableDestinataire.Constante::spliter.$codeEnr.Constante::spliter.$cs['CHP_DESTI'];

                if (empty($post[$inputName])) {
                    $post[$inputName] = $cs['CS_VALEUR'];
                }
            }
        }
    }

    /**
     * @param string $tableSource
     * @param string|array<string> $id
     * @param string|null $codeSte
     * @return string
     * @throws Exception
     */
    private function getSourceCodeEnr(string $tableSource, string|array $id, ?string $codeSte = null): string
    {
        if (in_array($tableSource, ['SECTIMPU', 'CODECOMP', 'SSCPTANA', 'CODGEST']) && is_string($id)) {
            $id = ChampSupp::autoCompletCodeEnrImputations($this->pdo, $tableSource, $id, $codeSte);
        }

        return ChampSupp::encodeCodeEnr($tableSource, $id);
    }
}
