<?php

// Si on est pas exécuté depuis la ligne de commande, ou si la mauvaise secure_key est envoyée, on arrête tout !
if ('cli' != php_sapi_name()) {
    die(1);
}

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

/////////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.inc.php';

    // Gestion multi-boutique (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
$context->controller = (object) [
    'controller_type' => 'cron',
];

$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);
