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

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function column_exists(mysqli $mysqli, string $table, string $column): bool {
    $tableEsc = $mysqli->real_escape_string($table);
    $colEsc   = $mysqli->real_escape_string($column);
    $sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '{$tableEsc}' AND COLUMN_NAME = '{$colEsc}' LIMIT 1";
    $res = $mysqli->query($sql);
    return $res && $res->num_rows > 0;
}

$hasWarrantyFlag   = column_exists($mysqli, 'consumption_items', 'has_warranty');
$hasWarrantyMonths = column_exists($mysqli, 'consumption_items', 'warranty_months');

// datumi filter
$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, location FROM projects WHERE id=?");
$stmt->bind_param('i', $project_id);
$stmt->execute();
$stmt->bind_result($p_name, $p_location);
$stmt->fetch();
$stmt->close();

$warrantySelect = '';
if ($hasWarrantyFlag) {
    $warrantySelect .= ", ci.has_warranty";
}
if ($hasWarrantyMonths) {
    $warrantySelect .= ", ci.warranty_months";
    $warrantySelect .= ", CASE WHEN ";
    if ($hasWarrantyFlag) {
        $warrantySelect .= "COALESCE(ci.has_warranty,0)=1 AND ";
    }
    $warrantySelect .= "COALESCE(ci.warranty_months,0) > 0 THEN DATE_ADD(o.usage_date, INTERVAL ci.warranty_months MONTH) ELSE NULL END AS warranty_until";
}

// materijal stavke (red po red)
$sqlMat = "
SELECT o.id AS order_id, o.usage_date, o.note,
       i.code, i.name AS item_name,
       ci.quantity, ci.unit
       {$warrantySelect}
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);

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

$laborTotal = 0.0;
$laborRows = [];
if ($labRes) {
  while ($r = $labRes->fetch_assoc()) {
    $laborTotal += (float)$r['total_cost'];
    $laborRows[] = $r;
  }
}

function warranty_label_pdf2(array $row): string {
    $hasWarranty = !empty($row['has_warranty']) || (!empty($row['warranty_months']) && (int)$row['warranty_months'] > 0);
    if (!$hasWarranty) return '—';
    $parts = ['Da'];
    if (!empty($row['warranty_months'])) $parts[] = (int)$row['warranty_months'] . ' mj';
    if (!empty($row['warranty_until'])) {
        $dt = DateTime::createFromFormat('Y-m-d', substr((string)$row['warranty_until'], 0, 10));
        $parts[] = 'do ' . ($dt ? $dt->format('d.m.Y') : (string)$row['warranty_until']);
    }
    return implode(' • ', $parts);
}

// build html
$period = '';
if ($date_from_display || $date_to_display) {
  $period = 'Period: '.h($date_from_display ?: '...').' - '.h($date_to_display ?: '...');
}

ob_start();
?>
<!doctype html>
<html lang="hr">
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 12px; color:#111; }
    h1 { font-size: 18px; margin:0 0 6px 0; }
    .muted { color:#666; }
    table { width:100%; border-collapse: collapse; margin-top:8px; }
    th, td { border:1px solid #ccc; padding:6px; vertical-align: top; }
    th { background:#f2f2f2; font-size: 11px; }
    .right { text-align:right; }
    .section { margin-top:16px; }
  </style>
</head>
<body>
  <h1>Projektni izvještaj (materijal + rad)</h1>
  <div class="muted">
    Projekt: <strong><?php echo h($p_name); ?></strong>
    <?php if ($p_location) echo ' — '.h($p_location); ?>
    <?php if ($period) echo '<br>'.$period; ?>
    <br>Datum ispisa: <?php echo date('d.m.Y H:i'); ?>
  </div>

  <div class="section">
    <h2 style="font-size:14px;margin:0 0 6px 0;">Materijal (stavke)</h2>
    <table>
      <thead>
        <tr>
          <th style="width:10%;">Datum</th>
          <th style="width:8%;"># Nalog</th>
          <th style="width:10%;">Šifra</th>
          <th>Artikl</th>
          <th style="width:12%;" class="right">Količina</th>
          <th style="width:8%;">JM</th>
          <th style="width:16%;">Garancija</th>
          <th style="width:20%;">Napomena</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$matRes || $matRes->num_rows===0): ?>
        <tr><td colspan="8" class="muted">Nema stavki u odabranom periodu.</td></tr>
      <?php else: ?>
        <?php while($r=$matRes->fetch_assoc()):
          $dt = DateTime::createFromFormat('Y-m-d', $r['usage_date']);
          $dhr = $dt ? $dt->format('d.m.Y') : $r['usage_date'];
        ?>
        <tr>
          <td><?php echo h($dhr); ?></td>
          <td><?php echo (int)$r['order_id']; ?></td>
          <td><?php echo h($r['code']); ?></td>
          <td><?php echo h($r['item_name']); ?></td>
          <td class="right"><?php echo number_format((float)$r['quantity'], 3, ',', '.'); ?></td>
          <td><?php echo h($r['unit']); ?></td>
          <td><?php echo h(warranty_label_pdf2($r)); ?></td>
          <td><?php echo h($r['note']); ?></td>
        </tr>
        <?php endwhile; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <div class="section">
    <h2 style="font-size:14px;margin:0 0 6px 0;">Rad (sati)</h2>
    <table>
      <thead>
        <tr>
          <th>Djelatnik</th>
          <th>Radno mjesto</th>
          <th class="right" style="width:18%;">Sati</th>
          <th class="right" style="width:18%;">Iznos (€)</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($laborRows)): ?>
          <tr><td colspan="4" class="muted">Nema evidentiranih sati rada u odabranom periodu.</td></tr>
        <?php else: ?>
          <?php foreach($laborRows as $lr): ?>
            <tr>
              <td><?php echo h($lr['first_name'].' '.$lr['last_name']); ?></td>
              <td><?php echo h($lr['job_title']); ?></td>
              <td class="right"><?php echo number_format((float)$lr['total_hours'], 2, ',', '.'); ?></td>
              <td class="right"><?php echo number_format((float)$lr['total_cost'], 2, ',', '.'); ?></td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
      <tfoot>
        <tr>
          <th colspan="3" class="right">UKUPNO RAD</th>
          <th class="right"><?php echo number_format((float)$laborTotal, 2, ',', '.'); ?></th>
        </tr>
      </tfoot>
    </table>
  </div>
</body>
</html>
<?php
$html = ob_get_clean();

// Try Dompdf
$autoloads = [
  __DIR__.'/vendor/autoload.php',
  __DIR__.'/../vendor/autoload.php',
  __DIR__.'/dompdf/autoload.inc.php',
  __DIR__.'/lib/dompdf/autoload.inc.php'
];
$loaded = false;
foreach ($autoloads as $a) {
  if (file_exists($a)) { require_once $a; $loaded = true; break; }
}

if ($loaded && class_exists('\\Dompdf\\Dompdf')) {
  $dompdf = new \\Dompdf\\Dompdf(['isRemoteEnabled' => true]);
  $dompdf->loadHtml($html, 'UTF-8');
  $dompdf->setPaper('A4', 'portrait');
  $dompdf->render();
  $dompdf->stream('projekt_'.$project_id.'_izvjestaj.pdf', ['Attachment' => false]);
  exit;
}

// Fallback: show printable HTML
header('Content-Type: text/html; charset=utf-8');
echo $html;
