<?php

include "../../root.class.php";
$functions = new functions();
$total_stock_value = 0.00;
$db = new db_safeguard();

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

$output = fopen('php://output', 'w');

// Add the header row
fputcsv($output, [
    'STATUS',
    'ORDER ID',
    'ASSET',
    'ODO',
    'USER',
    'OPENED',
    'CLOSED',
    'AMOUNT (L)',
    'TANK'
]);

$data = $_GET['where_data'];

$latest_orders_res = $db->query("fuel_movement", "SELECT * FROM fuel_movement WHERE $data ORDER BY record_id DESC");
$total_amount = 0;
$transactions_total = 0;

while ($latest_orders = $latest_orders_res->fetch_assoc()) {
    fputcsv($output, [
        $latest_orders['status'],
        $latest_orders['order_id'],
        $functions->get_asset_name($latest_orders['asset_id']),
        $latest_orders['odo'],
        $functions->get_username($latest_orders['user_id']),
        $latest_orders['date_time_opened'],
        $latest_orders['date_time_closed'],
        ($latest_orders['amount'] / 1000) . " L",
        $functions->get_tank_name($latest_orders['tank_id'])
    ]);

    $total_amount += $latest_orders['amount'];
    $transactions_total++;
}

// Add the totals row
fputcsv($output, [
    'TOTAL',
    '',
    '',
    '',
    '',
    '',
    ($total_amount / 1000) . " L",
    $transactions_total
]);

fclose($output);
exit;
