<?php
require_once 'config.php';
require_login();
require_permission('orders');

$project_filter = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;
$date_from_display = trim($_GET['date_from'] ?? '');
$date_to_display   = trim($_GET['date_to'] ?? '');

$date_from_sql = '';
$date_to_sql   = '';

if ($date_from_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_from_display);
    if ($dt) $date_from_sql = $dt->format('Y-m-d');
}
if ($date_to_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_to_display);
    if ($dt) $date_to_sql = $dt->format('Y-m-d');
}

$where = [];
if ($project_filter > 0) {
    $where[] = 'o.project_id = ' . $project_filter;
}
if ($date_from_sql !== '') {
    $where[] = "o.usage_date >= '" . $mysqli->real_escape_string($date_from_sql) . "'";
}
if ($date_to_sql !== '') {
    $where[] = "o.usage_date <= '" . $mysqli->real_escape_string($date_to_sql) . "'";
}
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "SELECT o.id, o.usage_date, o.note, p.name AS project_name
        FROM consumption_orders o
        JOIN projects p ON p.id = o.project_id
        $where_sql
        ORDER BY o.usage_date DESC, o.id DESC";
$res = $mysqli->query($sql);

header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="nalozi_' . date('Ymd_His') . '.xls"');

echo "ID\tDatum\tProjekt\tNapomena\n";
while ($o = $res->fetch_assoc()) {
    $dt = DateTime::createFromFormat('Y-m-d', $o['usage_date']);
    $date_hr = $dt ? $dt->format('d.m.Y') : $o['usage_date'];

    echo $o['id'] . "\t" .
         $date_hr . "\t" .
         $o['project_name'] . "\t" .
         $o['note'] . "\n";
}
exit;
