<?php

namespace Modules\Stock\Service\Form;

use Entity\Model\Sarticle;
use Entity\Model\SbtLign;
use Entity\Model\SbtLots;
use Exception;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Modules\Stock\Interface\FormServiceInterface;
use Modules\Stock\Interface\TracableStockArticleInterface;
use Modules\Stock\Trait\FormTrait;
use PDO;

readonly class LigneBonTransfertFormService implements FormServiceInterface, TracableStockArticleInterface
{
    use FormTrait;
    public function __construct(private PDO $pdo)
    {
    }

    /**
     * @param array<string,mixed> $post
     * @param array<string,mixed> $data
     * @return array<string,mixed>
     * @throws Exception
     */
    public function initEntity(array $post, array $data = []): array
    {
        $post['NO_BT'] = $data['NO_BT'];
        $post['PRIX'] = $post['PRIX'] ?? 0;
        $post['REAPPRO_FAIT'] = false;
        unset($post['DUPLICATE']);

        return $post;
    }

    /**
     * @param array<string,mixed> $entity
     * @param array<string,mixed> $post
     * @return void
     * @throws Exception
     */
    public function flushData(array $entity, array $post = []): void
    {
        $stockArticle = (new Sarticle($this->pdo))->find(['CODE_ART' => $entity['CODE_ART']]);

        $this->pdo->beginTransaction();

        (new SbtLign($this->pdo))->processAndMerge($entity);
        ChampSupp::updateCS($post, $this->pdo);
        $this->updateResteLigneDemandeService($entity, $post['QTE_TRF_VAR']);
        $this->updateQteReserveeStockLocal($entity, $post['QTE_TRF_VAR'], $post['BON_TRANSFERT']['SITE'], 'CODE_ART');
        $this->updateLotsCollection($stockArticle, $entity, $post);

        $this->pdo->commit();
    }

    /**
     * @param array<string,mixed> $stockArticle
     * @param array<string,mixed> $entity
     * @param array<string,mixed> $post
     * @return void
     */
    public function updateLotsCollection(array $stockArticle, array $entity, array $post = []): void
    {
        if (Sql::toBool($stockArticle['TRACABLE'])) {
            $sbtlots = new SbtLots($this->pdo);
            $sbtlots->delete(['NO_BT' => $entity['NO_BT'], 'NO_LIG_BT' => $entity['NO_LIG']]);

            foreach ($post['SBT_LOTS'] as $lotsBonTransfert) {
                $lotsBonTransfert['NO_BT'] = $entity['NO_BT'];
                $lotsBonTransfert['NO_LIG_BT'] = $entity['NO_LIG'];
                $lotsBonTransfert['CODE_ART'] = $entity['CODE_ART'];
                $sbtlots->merge($lotsBonTransfert);
            }
        }
    }
}
