<?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);
}

// Désactivation du timeout
set_time_limit(0);

// ///////////////////////////////////////////////
// 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;
}

$context = Context::getContext();

// Workaround pour PrestaShop
// @phpstan-ignore-next-line
$context->controller = (object) [
    'controller_type' => 'cron',
    'php_self' => 'export_compta',
];

$db = Db::getInstance();

// ///////////////////////////////////////////////
// Requête qui isole toutes les commandes
$lines = $db->executeS(
    '
SELECT
  MIN(invoice_date) AS `date`,
  MAX(invoice_number) AS `num_facture`,
  ROUND(SUM(total_paid_real), 2) AS PVTTC,
  ROUND(SUM(total_products) + SUM(total_shipping_tax_excl), 2) AS PVHT,
  ROUND(SUM(total_discounts_tax_incl), 2) AS RTTC,
  NULL AS TxR,
  ROUND(SUM(total_discounts_tax_excl), 2) AS RHT,
  ROUND(SUM(total_paid_tax_incl) -  SUM(total_paid_tax_excl), 2) AS TVA
FROM `' . _DB_PREFIX_ . '_orders`
WHERE
  reference IS NOT NULL
  AND secure_key != -1
  AND invoice_number != 0
GROUP BY reference
ORDER BY `date` DESC'
);

if (!is_array($lines)) {
    $lines = [];
}

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export_compta.csv');

$stream = fopen('php://temp', 'r+');

if (!$stream) {
    echo 'Erreur lors de la création du fichier.';
    exit;
}

fputcsv($stream, ['date', 'journal', 'compte', 'intitule', 'nofacture', 'debit', 'credit'], ';');

foreach ($lines as $line) {
    fputcsv($stream, [date('d/m/Y', strtotime($line['date'])), 'VI', '7071105', 'Vente internet', $line['num_facture'], '', $line['PVHT']], ';');
    fputcsv($stream, [date('d/m/Y', strtotime($line['date'])), 'VI', '7097', 'Vente internet', $line['num_facture'], $line['RHT'], ''], ';');
    fputcsv($stream, [date('d/m/Y', strtotime($line['date'])), 'VI', '4457146', 'Vente internet', $line['num_facture'], '', $line['TVA']], ';');
    fputcsv($stream, [date('d/m/Y', strtotime($line['date'])), 'VI', '4110001', 'Vente internet', $line['num_facture'], $line['PVTTC'], ''], ';');
}

rewind($stream);
echo stream_get_contents($stream);
fclose($stream);
