<?php

namespace Modules\Stock\Service\Form;

use Entity\Model\Societe;
use Entity\Model\SSiteSto;
use Exception;
use Helpers\ChampsSupplementaire\ChampSupp;
use Modules\Stock\Interface\FormServiceInterface;
use Modules\Stock\Trait\FormTrait;
use PDO;

readonly class SiteStockFormService implements FormServiceInterface
{
    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['ADR'] = '';
        $post['VILLE'] = '';
        $post['NB_ART'] = 0;
        $post['COUT_ORD'] = 0;
        $post['TX_POSS'] = 1;
        $post['DELAI_INT'] = 0;
        $post['DTE_REAP'] = '00000000';
        $post['CUM_CONSO'] = 0;
        $post['CUM_JANV'] = 0;
        $post['MARK_UP'] = 0;
        $post['DEVISE'] = (new Societe($this->pdo))->find(['CODE_STE' => $post['CODE_STE']])['DEVISE'];
        $post['FRAIS'] = 0;
        $post['SIST_DTE_FERM'] = '00000000';
        $post['CODGES'] = '';
        $post['LIBGES'] = '';
        $post['ID_CG'] = '';

        return $post;
    }

    /**
     * @param array<string,mixed> $entity
     * @param array<string,mixed> $post
     * @return void
     */
    public function flushData(array $entity, array $post = []): void
    {
        $this->pdo->beginTransaction();

        (new SSiteSto($this->pdo))->merge($entity);
        ChampSupp::updateCS($post, $this->pdo);

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