<?php

namespace App\Command;

use App\Entity\Order;
use App\Helper\Hiltes;
use App\Repository\OrderRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'hiltes:export',
    description: 'Erstellt die Hiltes-Exportdatei aus den aktuellen Bestelldaten',
)]
class HiltesExportCommand extends Command
{
    public function __construct(OrderRepository $orderRepository, LoggerInterface $logger, private Hiltes $hiltes)
    {
        $this->orderRepository = $orderRepository;
        $this->logger = $logger;

        parent::__construct();
    }


    protected function configure(): void
    {
        $this
            ->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description');
    }

    /**
     * Schreibt die Hiltes Expport Datei
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {

        $io = new SymfonyStyle($input, $output);

        $io->info('Start Hiltes Export');

        $l = $this->hiltes->loginToHiltes('', '');
        if (!$l) {
            dd('Login faild' . 'STOP ' . __METHOD__ . ' / ' . __LINE__);
        }
        /**
         * @var Order
         */
        $orders = $this->orderRepository->findAll();
        #dump($orders);


        foreach ($orders as $order) {
            if ($order->getStatus() > 0) continue;
            $tA = $order->getData();#json_decode($order->getData());
            $tA['orderdate'] = "2023-08-30T12:05:24.000Z";

            #dd($order->getData());
            #dd(array(
            #	'orderdate'=> $tA['orderdate'],
            #	'time'=> strtotime($tA['orderdate']),
            #	'gmdate '=> gmdate ('d-m-Y\TH:i:s.v\Z',strtotime($tA['orderdate'])),
            #));
            #*** Umkonvertieren des Datumstings *****************
            $tA['orderdate'] = gmdate('Y-m-d\TH:i:s.v\Z', strtotime($tA['orderdate']));
            #****
            $arr = array(
                'SalesDate' => $tA['orderdate'],
                "BranchNumber" => 8, #Die Filialnummer
                "ShopNumber" => 1, #Die Shopnummer
                "DistributionChannel" => 5, #Der Vertriebskanal
                'SaleList' => array(),
                'CustomerList' => array(),
            );
            #*** Items ***************
            if (!empty($tA['data']) && is_array($tA['data'])) {
                # Noch nötig
                #			"CalculatedSellingPrice" => 0, #X Kalkulierter Verkaufspreis
                #			"AchievedSalesPrice" => 0, #X Erzielter Verkaufspreis
                $tSalNr = array();
                foreach ($tA['data'] as $v) {
                    $SalesNumber = (!empty($v['gtin']) ? $v['gtin'] : $v['sku']);
                    if (preg_match('/^([0-9]+)_/', $SalesNumber, $tP)) {
                        $SalesNumber = $tP[1];
                    }
                    if (isset($tSalNr[$SalesNumber])) {
                        $tSalNr[$SalesNumber]++;
                        $SalesNumber .= $tSalNr[$SalesNumber];
                    } else {
                        $tSalNr[$SalesNumber] = 0;
                    }
                    #dump($SalesNumber);
                    #********
                    $v['CalculatedSellingPrice'] = 100.00;
                    $v['AchievedSalesPrice'] = 90.00;
                    $arr['SaleList'][] = array(
                        "SalesLabel" => 'Ean',#$v['sku'],#X
                        "SalesLabelNumber" => $SalesNumber,#X
                        "SalesGoodsGroupNumber" => 0,
                        "SizeDescription" => '',#"string",
                        "CustomerNumber" => 0,
                        "TypeOfEstate" => 0,
                        "Amount" => $v['menge'],#X
                        "CalculatedSellingPrice" => $v['CalculatedSellingPrice'], #X Kalkulierter Verkaufspreis
                        "AchievedSalesPrice" => $v['AchievedSalesPrice'], #X Erzielter Verkaufspreis
                        "TransactionType" => "Sale", #X Die Vorgangsart Sale=Verkauf Exchange=Umtausch / Storno
                        "ReceiptNumber" => 0, #Die Belegnummer
                        "DateOfSale" => $tA['orderdate'],#X  das Verkaufsdatum mit Verkaufszeit
                        "PaymentMethod" => 'Invoice',#X "CreditCard",
                        "Currency" => 'EUR',#X "string",
                        "Unit" => "Piece",#X
                        "DistributionChannel" => 'JTL',#"string"
                    );

                }
            }
            #*** Kundne *******************************
            $arr['CustomerList'][] = array(
                "CustomerNumber" => 99999, # Fake Daten
                "Surname" => 'MAX',#"string",
                "Forename" => 'MUSTERMANN',#"string",
                "AddressCity" => 'ERFURT',#"string",
                "AddressZipCode" => '99084', "string",
                "AddressStreet" => 'MusterStrasse 22',#"string",
                "AddressCountry" => 'DE',#"string",
                #*** Nicht nötig
                #"CardNumber" => 0,
                #"SalutionNumber" => 0,
                #"PostOfficeBox" => '',#"string",
                #"PostOfficeBoxZipCode" => '',#"string",
                #"Title" => '',#"string",
                #"PhoneNumber1" => '',#"string",
                #"PhoneNumber2" => '',#"string",
                #"FaxNumber" => '',#"string",
                #"BirthDay" => '',#"2023-09-14T11:54:26.708Z",
                #"Gender" => 'Male',
                #"EmailAddress" => '',#"string",
                #"Discount" => 0,
                #"Limit" => 0,
                #"LockMark" => 'Unblocked',
                #"DubiousMark" => 'Undubious',
                #"DubiousText" => '',#"string",
                #"DirectDebit" => '',#true,
                #"BankName1" => '',#"string",
                #"BankAccountNumber1" => '',#"string",
                #"BankCodeNumber1" => '',#"string",
                #"BankName2" => '',#"string",
                #"BankAccountNumber2" => '',#"string",
                #"BankCodeNumber2" => '',#"string",
                #"BankName3" => '',#"string",
                #"BankAccountNumber3" => '',#"string",
                #"BankCodeNumber3" => '',#"string",
                #"CreditcardNumber1" => '',#"string",
                #"CreditcardNumber2" => '',#"string",
                #"CreditcardNumber3" => '',#"string",
                #"CreditcardNumber4" => '',#"string",
                #"ChangeIndicator" => '',#true,
                #"Newsletter" => '',#true,
                #"Password" => '',#"string",
                #"AdBan" => '',#true
            );
            $data = $this->hiltes->createJson($arr);
        }


        $this->hiltes->sendOrderToHiltes($data);


        $io->success('Done!');

        return Command::SUCCESS;
    }
}