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

require_once __DIR__ . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;

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

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

$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);
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);

$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";
}

$sql = "
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_items ci
JOIN consumption_orders o ON o.id = ci.order_id
JOIN items i ON i.id = ci.item_id
{$where_sql}
ORDER BY o.usage_date, o.id, i.name
";
$res = $mysqli->query($sql);
$rows = [];
while ($res && ($r = $res->fetch_assoc())) {
    $rows[] = $r;
}
$today = date('d.m.Y');

function warranty_label_pdf(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);
}

ob_start();
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body { font-family: DejaVu Sans, sans-serif; font-size: 11px; }
        h1 { font-size: 16px; margin-bottom: 4px; }
        p { margin: 2px 0; }
        table { border-collapse: collapse; width: 100%; margin-top: 8px; }
        th, td { border: 1px solid #000; padding: 3px; }
        th { background: #eee; font-size: 10px; }
        td { font-size: 10px; }
        .right { text-align: right; }
    </style>
</head>
<body>
<h1>Utrošak materijala po projektu</h1>
<p><strong>Projekt:</strong> <?php echo htmlspecialchars($p_name); ?>
<?php if ($p_location): ?> • <?php echo htmlspecialchars($p_location); ?><?php endif; ?></p>
<p><strong>Datum izvještaja:</strong> <?php echo $today; ?></p>
<?php if ($date_from_display || $date_to_display): ?>
    <p><strong>Razdoblje:</strong>
        <?php echo $date_from_display ?: '—'; ?> - <?php echo $date_to_display ?: '—'; ?>
    </p>
<?php endif; ?>

<?php if (empty($rows)): ?>
    <p>Nema stavki za zadane kriterije.</p>
<?php else: ?>
<table>
    <thead>
    <tr>
        <th>Datum</th>
        <th># Nalog</th>
        <th>Šifra</th>
        <th>Artikl</th>
        <th>Količina</th>
        <th>JM</th>
        <th>Garancija</th>
        <th>Napomena naloga</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($rows as $row):
        $dt = DateTime::createFromFormat('Y-m-d', $row['usage_date']);
        $date_hr = $dt ? $dt->format('d.m.Y') : $row['usage_date'];
    ?>
        <tr>
            <td><?php echo $date_hr; ?></td>
            <td><?php echo $row['order_id']; ?></td>
            <td><?php echo htmlspecialchars($row['code']); ?></td>
            <td><?php echo htmlspecialchars($row['item_name']); ?></td>
            <td class="right"><?php echo number_format((float)$row['quantity'], 3, ',', '.'); ?></td>
            <td><?php echo htmlspecialchars($row['unit']); ?></td>
            <td><?php echo htmlspecialchars(warranty_label_pdf($row)); ?></td>
            <td><?php echo htmlspecialchars($row['note']); ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<p style="margin-top:10px;font-size:9px;">Generirano iz aplikacije za evidenciju materijala.</p>
</body>
</html>
<?php
$html = ob_get_clean();

$dompdf = new Dompdf();
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$filename = 'projekt_utrosak_' . $project_id . '_' . date('Ymd_His') . '.pdf';
$dompdf->stream($filename, ['Attachment' => 0]);
exit;
