<?php

namespace Modules\Facture\Outil;

use Entity\Model\Articles;
use Entity\Model\Country;
use Entity\Model\FacLig;
use Entity\Model\FacLigTravail;
use Entity\Model\Fourniss;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Modules\Facture\Repository\CreationFacture as RepositoryCreationFacture;
use SimpleXMLElement;

class CreationFacture
{

    public static function getTxDevise($pdo, $params)
    {
        // Taux devise entre devise BDD et devise facture
        $devise = new \Entity\Model\Devise($pdo);
        $taux['TX_DEVISE'] = floatval($devise->find($params['deviseFacture'])['VALEUR']);

        // Taux devise entre devise société et devise facture
        if ($params['deviseBDD'] == $params['deviseSociete']) {
            $taux['TX_DEVSTE'] = $taux['TX_DEVISE'];
        } elseif ($params['deviseSociete'] == $params['deviseFacture']) {
            $taux['TX_DEVSTE'] = floatval(1);
        } else {
            $Txdevpivot = new \Entity\Model\Txdevpivot($pdo);
            $taux['TX_DEVSTE'] = floatval($Txdevpivot->find(['DEV_PIVOT' => $params['deviseSociete'], 'DEV_A_CONV' => $params['deviseFacture']])['TAUX'] ?? 0);
        }

        return $taux;
    }

    /**
     * Permet de d'ajouter
     *
     * @param \PDO $pdo
     * @param array<array<string|int>> $listes
     * @param array<string|int> $paramsGlobal
     *
     * @return void
     */
    public static function insertListeArticleSansCommande($pdo, $listes, $paramsGlobal)
    {

        $facLigTravail = new FacLigTravail($pdo);
        $ligne = 1;
        $Articles = new Articles($pdo);

        // Vérification si le pays est CE pour init ou non la TVA en fonction de l'article
        $Fourniss = new Fourniss($pdo);
        $actualFourniss = $Fourniss->find(['CODE' => $paramsGlobal['CODE_FOUR']]);

        $Country = new Country($pdo);
        $isCountryCE = sql::boolSql2($Country->find(['CODE_PAYS' => $actualFourniss['CODE_PAYS']])["PAYSCEE"]);
        
        $txTva = ($paramsGlobal["TOTAL_HT"] !== $paramsGlobal["TOTAL_TTC"]) || ($isCountryCE == "T") ? true : false;

        //Vérifier s'il n'y a pas moyen de mieux gérer les floats lors des divisions

        $listeDesMontants = [];
        $totalHT = sprintf("%.2f", $paramsGlobal["TOTAL_HT"]);

        foreach ($listes as $key => $liste) {
            $liste["MONTANT"] = sprintf("%.2f", ((floatval($totalHT) * floatval($liste["POURCENTAGE"])) / 100.00));
            $listeDesMontants[] = $liste["MONTANT"];

            if (array_key_last($listes) === $key) {
                $totalMontants = (string) round(array_sum($listeDesMontants), 2);
                if ($totalHT !== $totalMontants) {
                    $liste["MONTANT"] += ($totalHT - $totalMontants);
                    $liste["MONTANT"] = (string) round($liste["MONTANT"], 2);
                }
            }
            
            $article = $Articles->find(["CODE_ART" => $liste["CODE_ART"]]);
            $article["TXTVA"] = $txTva ? $article["TXTVA"] : 0;

            $insert[] = $facLigTravail->insert([
                "NUM_FACT"                      => (int) $paramsGlobal['NUM_FACT'],
                "NUM_LIG"                       => $ligne,
                "NUM_CDE"                       => 0,
                "NUM_LICDE"                     => 0,
                "NUM_BR"                        => 0,
                "NUM_LIBR"                      => 0,
                "NUM_TERME"                     => 0,
                "DESIGNAT"                      => $liste["DESIGN"],
                "CODE_SFAM"                     => $liste["SSFAM"],
                "TP_QUANT"                      => Sql::boolSql2(false), //TODO : A vérifier
                "QUANTITE"                      => floatval(1),
                "PU_REMISE"                     => floatval(0), // TODO: Voir avec MSA
                "MONTANT"                       => floatval($liste["MONTANT"]),
                "CODE_SI"                       => $liste["SI"] ?? "",
                "CODE_CDC"                      => $liste["CDC"] ?? "",
                "CODE_SCA"                      => $liste["SCA"] ?? "",
                "CODE_PROFIL_TVA"               => "",
                "TYPE_TVA"                      => $liste["TYP_TVA"] ?? "",
                "TAUX_TVA"                      => floatval($article["TXTVA"]),
                "REF_FACT"                      => 0,
                "BL_FOURN"                      => "",
                "CODE_STE"                      => $paramsGlobal["societe"],
                "NUM_EXP"                       => 0,
                "NOLIGEXP"                      => 0,
                "DATEMODI"                      => '00000000',
                "AFF_TMP"                       => Sql::boolSql2(false), //TODO : A vérifier
                "LIG_ERR"                       => Sql::boolSql2(false), //TODO : A vérifier
                "REFARTFOU"                     => "",
                "ID_CG"                         => "",
                "MT_TVA"                        => floatval(($liste["MONTANT"] * floatval($article["TXTVA"])) / 100),
                "SELECTIONNEE"                  => Sql::boolSql2(true),
                "PRESENCE_INCIDENT_FOURNISSEUR" => Sql::boolSql2(false),
                "RECEP_EN_MONTANT"              => Sql::boolSql2(false),
                "DESCOMP"                       => '',
                "LIG_MAN"                       => Sql::boolSql2(false),
                "QUANTITE_INIT"                 => 1,
                "PU_REMISE_INIT"                => 0,
                "MONTANT_INIT"                  => 0,
                "TAUX_TVA_INIT"                 => 0,
                "MT_TVA_INIT"                   => 0
            ]);

            $initCs = ChampSupp::initCs('FAC_LIG', 'SSFAMILL', (string)$liste["SSFAM"], $pdo);
            foreach ($initCs as $cs) {
                ChampSupp::updateChampSupp(
                    'FAC_LIG_TRAVAIL',
                    ChampSupp::autoCompletCodeEnr((string)$paramsGlobal['NUM_FACT'], $ligne, 'FAC_LIG'),
                    $cs['CHP_DESTI'],
                    $cs['CS_VALEUR'],
                    $pdo
                );
            }

            $ligne++;
        }
    }
}
