<?php

namespace Myvetshop\Module\Clinique\Command\Accounting;

use Myvetshop\Module\Clinique\Accounting\Export\AccountingExporter;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class AccountingExportCommand extends Command
{
    private AccountingExporter $accountingExporter;

    protected function configure(): void
    {
        $this
            ->setDescription('Réalise un export comptable pour les dates indiquées')
            ->addArgument('start_date', InputArgument::REQUIRED, 'Date de début incluse (Y-m-d)')
            ->addArgument('end_date', InputArgument::REQUIRED, 'Date de fin incluse (Y-m-d)');
    }

    public function __construct(AccountingExporter $accountingExporter)
    {
        $this->accountingExporter = $accountingExporter;

        parent::__construct('app:accounting:export');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $styledOutput = new SymfonyStyle($input, $output);

        $startDateRaw = $input->getArgument('start_date');
        if (!is_string($startDateRaw)) {
            throw new \Exception('Invalid start date');
        }
        $endDateRaw = $input->getArgument('end_date');
        if (!is_string($endDateRaw)) {
            throw new \Exception('Invalid end date');
        }

        $startDate = \DateTimeImmutable::createFromFormat(
            'Y-m-d',
            $startDateRaw
        );
        $endDate = \DateTimeImmutable::createFromFormat(
            'Y-m-d',
            $endDateRaw
        );

        if (!$startDate || !$endDate) {
            $styledOutput->error('Invalid dates provided');

            return 1;
        }

        $stats = $this->accountingExporter->getStats($startDate, $endDate);

        $styledOutput->title('Statistics :');
        $styledOutput->listing([
            'Invoice number : ' . $stats['nbInvoices'],
            'Slip number : ' . $stats['nbSlips'],
            'Errors : ' . $stats['nbErrors'],
            'Lines : ' . $stats['nbLines'],
        ]);

        if (\count($stats['errors'])) {
            $styledOutput->title('Errors :');
            $styledOutput->listing($stats['errors']);
        }

        $exportFile = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . \time() . '.csv';

        $styledOutput->text('Saving export to : ' . $exportFile);

        $exportOutput = \fopen($exportFile, 'w');
        if (!$exportOutput) {
            throw new \Exception("Can't open output file for writing");
        }

        $export = $this->accountingExporter->getCsv($startDate, $endDate);

        \stream_copy_to_stream($exportOutput, $export);
        \fclose($exportOutput);
        \fclose($export);

        $styledOutput->success('Export save successfully');

        return 0;
    }
}
