
<?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.');

$date_from_display = trim($_GET['date_from'] ?? '');
$date_to_display   = trim($_GET['date_to'] ?? '');

$where = "WHERE o.project_id = {$project_id}";
if ($date_from_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_from_display);
    if ($dt) $where .= " AND o.usage_date >= '".$dt->format('Y-m-d')."'";
}
if ($date_to_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_to_display);
    if ($dt) $where .= " AND o.usage_date <= '".$dt->format('Y-m-d')."'";
}

// projekt
$stmt = $mysqli->prepare("SELECT name FROM projects WHERE id=?");
$stmt->bind_param('i', $project_id);
$stmt->execute();
$stmt->bind_result($p_name);
$stmt->fetch();
$stmt->close();

$sqlMat = "
SELECT o.id AS order_id, o.usage_date, o.note,
       i.code, i.name AS item_name,
       ci.quantity, ci.unit
FROM consumption_orders o
JOIN consumption_items ci ON ci.order_id=o.id
JOIN items i ON i.id = ci.item_id
{$where}
ORDER BY o.usage_date, o.id, i.name
";
$matRes = $mysqli->query($sqlMat);

$sqlLab = "
SELECT o.id AS order_id, l.work_date,
       e.first_name, e.last_name, e.job_title,
       l.hours, l.hourly_rate,
       (l.hours*l.hourly_rate) AS total_cost,
       l.note
FROM consumption_labor l
JOIN consumption_orders o ON o.id=l.order_id
JOIN employees e ON e.id=l.employee_id
{$where}
ORDER BY l.work_date, o.id, e.last_name
";
$labRes = $mysqli->query($sqlLab);

// autoload PhpSpreadsheet
$autoloads = [
  __DIR__.'/vendor/autoload.php',
  __DIR__.'/../vendor/autoload.php'
];
$loaded=false;
foreach($autoloads as $a){ if(file_exists($a)){ require_once $a; $loaded=true; break; } }
if(!$loaded || !class_exists('\PhpOffice\PhpSpreadsheet\Spreadsheet')){
  die('PhpSpreadsheet nije pronađen. Pokreni: composer require phpoffice/phpspreadsheet');
}

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();

// Sheet 1: Materijal
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Materijal');
$sheet1->fromArray(['Datum','Nalog','Šifra','Artikl','Količina','JM','Napomena'], null, 'A1');
$row=2;
if($matRes){
  while($r=$matRes->fetch_assoc()){
    $dt = DateTime::createFromFormat('Y-m-d', $r['usage_date']);
    $dhr = $dt ? $dt->format('d.m.Y') : $r['usage_date'];
    $sheet1->fromArray([
      $dhr,
      (int)$r['order_id'],
      $r['code'],
      $r['item_name'],
      (float)$r['quantity'],
      $r['unit'],
      $r['note']
    ], null, 'A'.$row);
    $row++;
  }
}
$sheet1->getStyle('A1:G1')->getFont()->setBold(true);
$sheet1->freezePane('A2');

// Sheet 2: Rad
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Rad');
$sheet2->fromArray(['Datum','Nalog','Djelatnik','Radno mjesto','Sati','Satnica','Iznos','Napomena'], null, 'A1');
$row=2;
if($labRes){
  while($r=$labRes->fetch_assoc()){
    $dt = DateTime::createFromFormat('Y-m-d', $r['work_date']);
    $dhr = $dt ? $dt->format('d.m.Y') : $r['work_date'];
    $sheet2->fromArray([
      $dhr,
      (int)$r['order_id'],
      $r['first_name'].' '.$r['last_name'],
      $r['job_title'],
      (float)$r['hours'],
      (float)$r['hourly_rate'],
      (float)$r['total_cost'],
      $r['note']
    ], null, 'A'.$row);
    $row++;
  }
}
$sheet2->getStyle('A1:H1')->getFont()->setBold(true);
$sheet2->freezePane('A2');

// Output
$fname = 'projekt_'.$project_id.'_materijal_rad.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.$fname.'"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
