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

$project_id = (int)($_GET['project_id'] ?? 0);
if ($project_id <= 0) {
    die('Projekt nije odabran.');
}

$stmt = $mysqli->prepare("SELECT name FROM projects WHERE id = ?");
$stmt->bind_param('i', $project_id);
$stmt->execute();
$stmt->bind_result($p_name);
if (!$stmt->fetch()) {
    $stmt->close();
    die('Projekt nije pronađen.');
}
$stmt->close();

$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 = ["o.project_id = " . $project_id];
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 ' . implode(' AND ', $where);

$sql = "
SELECT
    i.code,
    i.name AS item_name,
    ci.unit,
    SUM(ci.quantity) AS qty_total
FROM consumption_items ci
JOIN consumption_orders o ON o.id = ci.order_id
JOIN items i ON i.id = ci.item_id
{$where_sql}
GROUP BY ci.item_id, i.code, i.name, ci.unit
ORDER BY i.name
";

$res = $mysqli->query($sql);

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

echo "Projekt:\t" . $p_name . "\n";
echo "Datum od:\t" . ($date_from_display ?: '') . "\n";
echo "Datum do:\t" . ($date_to_display ?: '') . "\n\n";

echo "Šifra\tArtikl\tUkupna količina\tJM\n";

while ($row = $res->fetch_assoc()) {
    $qty = str_replace('.', ',', number_format((float)$row['qty_total'], 3, '.', ''));
    echo $row['code'] . "\t" .
         $row['item_name'] . "\t" .
         $qty . "\t" .
         $row['unit'] . "\n";
}
exit;
