<?php

declare(strict_types=1);

// Si on n'est pas exécuté depuis la ligne de commande, on arrête tout !
if ('cli' != \PHP_SAPI) {
    exit(1);
}

// ///////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once __DIR__ . '/../../../config/config.inc.php';

    // Gestion multiboutique (au cas où) : Ce module est global
    if (Shop::isFeatureActive()) {
        Shop::setContext(Shop::CONTEXT_ALL);
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
    exit(1);
}

\Module::getInstanceByName('myvetshopclinique');

$display_usage = false;

if ($argc >= 3) {
    $startDate = \DateTimeImmutable::createFromFormat('Y-m-d', $argv[1]);
    $endDate = \DateTimeImmutable::createFromFormat('Y-m-d', $argv[2]);

    if (!$startDate || !$endDate) {
        $display_usage = true;
    }
} else {
    $display_usage = true;
    $startDate = null;
    $endDate = null;
}

if ($display_usage) {
    echo "Usage : php accounting_export.php [start_date] [end_date]\n";
    echo "\t start_date : Y-m-d (included)\n";
    echo "\t end_date : Y-m-d (included)\n";
    exit(1);
}

\assert($startDate instanceof \DateTimeImmutable);
\assert($endDate instanceof \DateTimeImmutable);

// Initialisation du container
global $kernel;
if (!$kernel) {
    require_once _PS_ROOT_DIR_ . '/app/AppKernel.php';
    $kernel = new \AppKernel('prod', false);
    $kernel->boot();
}

$container = \PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance();

if (!$container) {
    throw new \Exception("Can't get container");
}

/** @var \Myvetshop\Module\Clinique\Accounting\Export\AccountingExporter $accountingExporter */
$accountingExporter = $container->get(\Myvetshop\Module\Clinique\Accounting\Export\AccountingExporter::class);

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

echo "Statistics : \n";
echo "\t - Invoice number : " . $stats['nbInvoices'] . "\n";
echo "\t - Slip number : " . $stats['nbSlips'] . "\n";
echo "\t - Errors : " . $stats['nbErrors'] . "\n";
echo "\t - Lines : " . $stats['nbLines'] . "\n";

$output = \sys_get_temp_dir() . '/' . \time() . '.csv';

echo 'Saving export to : ' . $output . "\n";

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

\file_put_contents($output, \stream_get_contents($resource));
\fclose($resource);

echo "Done.\n";
