<?php
// read all csv files in directory
$dir = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/';
$files = scandir($dir);
$csvFiles = [];
foreach ($files as $file) {
    if (strpos($file, '.csv') !== false && strpos($file, '2025') == false) {
        $csvFiles[] = $file;
    }
}

// read files from csvFiles[] one by one
$report = [];
$sum = 0;
foreach ($csvFiles as $file) {
    $filename = $dir . $file;
    $handle = fopen($filename, 'r');
    if ($handle === false) {
        die('Cannot open file: ' . $filename);
    }

// && ($data[10] == 'FR00148_1000_amz_de' || $data[10] == 'FR00148') 
    while (($data = fgetcsv($handle, 0, "\t")) !== false) {
        if ($data[1] == 'Przemieszczenie - WDT' && $data[8] == 'PL' && $data[9] == 'CZ' && ($data[10] == 'FR00148_1000_amz_de' || $data[10] == 'FR00148') ) {
            $sum += intval($data[11]);
            $report[] = $data;
        }
    }
    fclose($handle);
}
var_dump($sum);
//var_dump($report);

die();
$outputFilename = $dir . '../report.csv';
$outputHandle = fopen($outputFilename, 'w');
if ($outputHandle === false) {
    die('Cannot open file for writing: ' . $outputFilename);
}

// Write header row if needed
if (!empty($report)) {
    fputcsv($outputHandle, array_keys($report[0]), "\t");
}

// Write data rows
foreach ($report as $row) {
    fputcsv($outputHandle, $row, "\t");
}

fclose($outputHandle);

?>